Setting pointers to NULL after free
What you'll learn: How to prevent accidental memory crashes by "neutralizing" pointers immediately after releasing their memory.
The "Zombie" Address
When you call free(ptr), you are telling the computer, "I am done with this memory; you can give it to someone else." The computer marks that memory as available, but it does not wipe the address stored inside your ptr variable.
Think of a pointer like a scrap of paper with a friend's home address written on it. Calling free() is like your friend moving out and the house being demolished. However, you still have the address written on your paper. If you try to visit that address later, you’re walking onto a construction site or into a stranger's living room. In C, this is a dangling pointer. If you accidentally try to read or write to it, your program will likely crash or, worse, corrupt random data.
Setting the Pointer to NULL
To prevent yourself from accidentally visiting a "demolished" address, you should always set the pointer to NULL immediately after freeing it. In C, NULL is a special value that represents "nowhere."
Checking a pointer against NULL is safe, and most modern systems will trigger a very clear, predictable crash if you try to access a NULL pointer, rather than the weird, unpredictable behavior of a dangling pointer.
#include <stdlib.h>
#include <stdio.h>
int main() {
int *data = malloc(sizeof(int));
*data = 42;
// Release the memory
free(data);
// CRITICAL STEP: Neutralize the pointer
data = NULL;
// Later in your code, you can safely check if it's usable
if (data != NULL) {
printf("Value: %d\n", *data);
} else {
printf("Pointer is safely empty.\n");
}
return 0;
}
Why this matters
By setting the pointer to NULL, you turn a dangerous "zombie" address into a clean, empty state. It’s a defensive programming habit. If you have a complex program where different functions might try to use the same pointer, setting it to NULL ensures that a simple if (ptr != NULL) check can prevent a catastrophic crash.
Key takeaway
Always follow free(ptr); with ptr = NULL; to ensure you don't accidentally use an address that no longer belongs to you.