Use-after-free vulnerabilities
What you'll learn: How to prevent serious security bugs caused by accessing memory that has already been released back to the system.
The "Expired Hotel Key" Problem
Imagine you check into a hotel and are given a key to Room 302. When your stay ends, you check out and return the key. A "use-after-free" bug is like keeping a secret copy of that key and trying to sneak back into the room later that night.
Even if the key still physically turns the lock, you no longer own that space. Another guest might be sleeping there, or the furniture might have been moved. If you try to change things in that room, you are corrupting someone else's data. In C, this leads to crashes, unpredictable behavior, and major security holes.
How it happens in code
When you call free(ptr), you are telling the computer: "I am done with this memory; feel free to give it to someone else." However, the pointer variable itself doesn't vanish. It still holds the address of that memory—it is now a dangling pointer.
If you try to read or write through that pointer after calling free(), you are committing a use-after-free error.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *message = malloc(20);
strcpy(message, "Hello World");
// Releasing the memory
free(message);
// USE-AFTER-FREE VULNERABILITY:
// The memory might be reused by another part of the program now.
// Accessing it here is dangerous and illegal.
printf("The message is: %s\n", message);
// BEST PRACTICE: Defensive coding
message = NULL;
return 0;
}
Why it is dangerous
Use-after-free errors are particularly nasty because they don't always cause an immediate crash. Your program might work fine during testing, but "glitch" in production when the memory is assigned to a different, sensitive variable (like a password buffer). An attacker can exploit this to redirect the program's flow or steal private data.
To prevent this, always treat a pointer as "dead" the moment you free it. Setting the pointer to NULL immediately after freeing it is a great habit, as it ensures that any accidental future use will cause a clear, immediate crash rather than a silent security breach.
Key takeaway
Never access a pointer after it has been freed; treat it as a broken tool and set it to NULL immediately to prevent accidental use.