top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Why should we assign NULL to the elements (pointer) after freeing them?

+4 votes
Why should we assign NULL to the elements (pointer) after freeing them?
posted Feb 27, 2014 by Kanika Prashar

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

This is paranoia based on long experience. After a pointer has been freed, you can no longer use the pointed-to data. The pointer is said to dangle; it doesn't point at anything useful. If you NULL out or zero out, a pointer immediately after freeing it, your program can no longer get in trouble by using that pointer. True, you might go indirect on the null pointer instead, but that's something your debugger might be able to help you with immediately. Also, there still might be copies of the pointer that refer to the memory that has been deallocated; that's the nature of C.
Zeroing out pointers after freeing them won't solve all problems.

We should set pointer to Null after freeing it because it can avoid memory corruption . A simple example is as follow ,

int *ptr= (int *)malloc(10);
free (ptr);
free (ptr); -- segmentation fault

Should be 
int *ptr= (int *)malloc(10);
free (ptr);
ptr = NULL;
free (ptr); -- No segmentation fault
answer Feb 27, 2014 by Hiteshwar Thakur