What is the difference between freeing the pointer and assigning it to NULL?

Sanjeev Kumar Dangi picture Sanjeev Kumar Dangi · Mar 12, 2010 · Viewed 13.7k times · Source

Could somebody tell me the difference between:

int *p;
p=(int*)malloc(10*sizeof(int));
free(p);

or

int *p;
p=(int*)malloc(10*sizeof(int));
p=NULL;

Answer

danben picture danben · Mar 12, 2010

free will deallocate the memory that p points to - simply assigning it to NULL will not (and thus you will have a memory leak).

It is worth mentioning that it is good practice to assign your pointer to NULL AFTER the call to free, as this will prevent you from accidentally trying to access the freed memory (which is still possible, but absolutely should not be done).