Dangling pointers after free
What you'll learn: How to prevent your program from crashing by safely clearing pointers after releasing their memory.
The "Library Card" problem
Imagine you have a library card that gives you access to a specific locker. When you return the key to the librarian, the locker is no longer yours. If you try to use your old knowledge of where that locker is to sneak back in and grab something, one of two things will happen: you’ll find the locker empty, or you’ll accidentally steal someone else’s stuff.
In C, when you call free(), you are returning the "key" (the memory) to the system. However, the pointer variable itself doesn't disappear; it still holds the address of that memory. This is called a dangling pointer. It’s a pointer that points to a "grave"—a place where data used to live, but is now off-limits.
The danger of the ghost address
If you try to access or modify a dangling pointer, your program might crash immediately (a Segmentation Fault). Even worse, the program might seem to work, but secretly corrupt other data because the system has already given that memory address to a different variable.
The safest way to handle this is to "zero out" the pointer immediately after freeing it. By setting the pointer to NULL, you turn a dangerous dangling pointer into a harmless null pointer.
Example: Free and Reset
Here is the safest way to handle memory deallocation:
#include <stdlib.h>
#include <stdio.h>
int main() {
// 1. Allocate memory
int *ptr = malloc(sizeof(int));
*ptr = 42;
// 2. Free the memory
free(ptr);
// AT THIS POINT: ptr is a "dangling pointer".
// It still holds the address, but we no longer own it.
// 3. The Safety Step: Set to NULL
ptr = NULL;
// Now, if we accidentally try to use ptr,
// the program will crash cleanly instead of corrupting data.
return 0;
}
Why this works
In C, it is perfectly legal to free(NULL). If you have a habit of setting pointers to NULL after freeing them, you prevent "double-free" errors (freeing the same memory twice) and ensure that any accidental use of the pointer is easy to debug.
Key takeaway
Always set a pointer to NULL immediately after calling free() to prevent it from pointing to reclaimed memory.