What is a dangling pointer
What you'll learn: You will learn why a pointer becomes "dangling" and why it is dangerous to use one after its memory has been released.
The Hotel Key Analogy
Imagine you check into a hotel and are given a key to Room 302. This key is your pointer—it holds the address of the room. When you check out, you give back the room, and the hotel staff prepares it for a new guest.
If you had secretly made a copy of that key, you would still have a way to open the door to Room 302, but you no longer "own" the space inside. If you walk back in, you might find a different family sleeping there, or the furniture might have been removed. Using that old key is dangerous and illegal.
In C, a dangling pointer is exactly like that copied key. It is a pointer that still holds a memory address, but the memory at that address has been freed or deleted.
How it happens in code
A dangling pointer usually appears when you use free() on a pointer but don't stop your program from trying to use that pointer later.
#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 the memory is gone.
// 3. Dangerous access (Invalid Access)
// printf("%d", *ptr); // This could crash or show garbage data!
// 4. The fix:
ptr = NULL;
return 0;
}
Why it is dangerous
When you free memory, you are telling the computer, "I'm done with this; feel free to give it to someone else." If you try to access that memory through your dangling pointer, one of two bad things will happen:
- Segmentation Fault: Your program crashes because it tried to touch memory it no longer owns.
- Silent Corruption: Your program doesn't crash, but it reads or writes data that now belongs to a different part of your program. This leads to bugs that are incredibly hard to track down because the error happens "quietly."
To prevent this, it is a best practice to set a pointer to NULL immediately after freeing it. This turns your "illegal key" into a "broken key" that the computer can easily identify as invalid.
Key takeaway
A dangling pointer is a pointer that points to a memory location that has been deallocated, making any attempt to use it unpredictable and dangerous.