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? )
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…