Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

How should I free a malloc variable when it has been assigned to another variable as well? (C Language)

Sorry if this has been asked already.

I have this program:

int main()
{
  int *X = (int *) malloc(sizeof(int));
  *X = 10; 
  int *Y = X;
  free(Y);

  return 0;
}

I don't know if the code is correct already or not. Do I still need to call free(X) as I have called malloc() for X? Do I need to call malloc() for Y as well, or is Y fine as it is?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This code is not correct because required header stdlib.h is not included and the result of malloc() is not checked. Also casting results of malloc() in C is discouraged.

Correct code is:

#include <stdlib.h>

int main(void)
{
  int *X = malloc(sizeof(int));
  if (X == NULL) return 1;
  *X = 10;
  int *Y = X;
  free(Y);

  return 0;
}

You don't need and mustn't call free(X); because X is pointing at the same point as Y and the memory is already freed by free(Y);.

You need to call malloc() for Y if you want Y point at different (new) thing than X. In this case freeing both what are pointed at by X and Y is recommended. (freeing will satisfy checkers like Valgrind, but in modern OS you don't have to free things at end of program execution because the OS will free up all memories used in your process. For more information, see c - What REALLY happens when you don't free after malloc? )


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...