After deallocating memory, set the pointer to NULL - C

Hello,

Could you please explain this? I didn't catch it.
Why should we set the pointer to NULL after deallocating memory?


After deallocating memory, set the pointer to NULL. This prevents accidentally referring to that memory, which may have already been allocated for another purpose.
1
2
free(newPtr);
newPtr = NULL;
Last edited on
It's to trap doing this.
1
2
3
4
5
6
7
free(newPtr);
newPtr = NULL;
/// more code

/// Then try to dereference it
newPtr[0] = something; 
newPtr->member = something;


By setting the pointer to NULL, you pretty much guarantee an instant trap should you try to make use of that pointer later on in the code.
It is by far better to set a pointer to NULL (which can be checked) then having it pointing to invalid memory.
Null is a special value that we give to pointers to signal that they do not point to anything. It is not necessary but it allows you to check if the pointer is null (there is no way to check if a pointer is uninitialized or dangling) and, like salem c said, if you accidentally try to dereference a null pointer it will usually crash the program instead of accessing deallocated memory (that might now be used by something else) and cause all kind of havoc.

If the pointer goes out of scope right after so that it cannot be used later then I would say it's not necessary to set it to null but if it is a pointer that lives on for longer it's usually a good idea to set it to null.
Last edited on
Topic archived. No new replies allowed.