Search code examples
cpointersfree

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


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;

Solution

  • 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).