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

Categories

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.4k views
Welcome To Ask or Share your Answers For Others

1 Answer

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? )


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...