Tracking down 'Use After Free' bugs
What you'll learn: How to use Valgrind to identify and fix errors where your code attempts to access memory that has already been released.
The "Zombie" Memory Problem
Imagine you check out a library book, read it, and then return it. If you later try to walk back into the library and read that same book while it's in someone else’s hands, you’re breaking the rules.
In C, a Use After Free (UAF) happens when you call free() on a pointer, but then try to read from or write to that pointer later in the program. Because that memory now belongs back to the system, your program might crash immediately, or worse, it might silently corrupt other data, creating bugs that are nearly impossible to track down without help.
Spotting the Bug with Valgrind
Valgrind acts like a security guard for your memory. When you run your program through it, Valgrind tracks every byte you allocate. If you try to touch memory that you have already "returned" via free(), Valgrind will scream.
Consider this buggy snippet:
#include <stdlib.h>
#include <stdio.h>
int main() {
int *scores = malloc(sizeof(int) * 3);
scores[0] = 95;
free(scores); // Memory is returned to the system
// DANGER: Using the pointer after freeing it
printf("My score was: %d\n", scores[0]);
return 0;
}
If you compile this with debug symbols (-g) and run valgrind ./my_program, you will see an error labeled:
Invalid read of size 4.
Valgrind will point exactly to the printf line and tell you that this memory was "freed by" a previous line. This tells you that while the pointer scores still holds an address, that address is no longer yours to use.
How to Fix It
The simplest way to prevent UAF bugs is to follow the "Free and Null" rule. Immediately after you free a pointer, set it to NULL.
free(scores);
scores = NULL;
By doing this, any accidental future use of scores will cause an immediate, predictable crash (a Segfault) rather than a mysterious "Use After Free" bug. Valgrind will also report a NULL pointer dereference, which is much easier to diagnose than corrupted data.
Key takeaway
Use Valgrind to catch "Invalid reads" after a free() call, and always set pointers to NULL after freeing them to prevent accidental access.