void getFree(void *ptr)
{
if(ptr != NULL)
{
free(ptr);
ptr = NULL;
}
return;
}
int main()
{
char *a;
a=malloc(10);
getFree(a);
if(a==NULL)
printf("it is null");
else
printf("not null");
}
Why is the output of this program not NULL?
Because the pointer is copied by value to your function. You are assigning
NULLto the local copy of the variable (ptr). This does not assign it to the original copy.The memory will still be freed, so you can no longer safely access it, but your original pointer will not be
NULL.This the same as if you were passing an
intto a function instead. You wouldn’t expect the originalintto be edited by that function, unless you were passing a pointer to it.If you want to null the original pointer, you’ll have to pass a pointer-to-pointer: