How should I free a malloc variable when it has been assigned to
another variable as well? (C Language)
You need not to free the declared variables (pointers) X
and Y
. They have automatic storage duration and will be freed automatically by the compiler when the control exits the scope where the variables are declared.
What you need is to free the dynamically allocated memory in this declaration
int *X = (int *) malloc(sizeof(int));
The memory was allocated one time and shall be freed also one time independent on how many pointers point to the allocated memory.
After this declaration
int *Y = X;
two pointers, X
and Y
, point now to the allocated memory.
To free the allocated memory you can use either of the pointers as for example
free( X );
or
free( Y );
After such a call the both pointers are dangling pointers. Usually it is a good idea to set such pointers to NULL
.
X = NULL;
Y = NULL;