Memory debugging with Valgrind
10 min lesson
- Valgrind is a tool that runs your program in a simulated environment and reports memory errors like leaks, use-after-free and out-of-bounds access.
- It matters because memory bugs are common in C and often silent; Valgrind catches them before they cause real damage.
- Think of Valgrind as a strict building inspector who walks through your program and writes a report on every unsafe thing it did.
- Valgrind tracks every allocation and free, and every read and write, so it can spot blocks that were never freed or used after freeing.
- A memory leak report shows the size and location of each block that is still allocated when the program ends.
- Use-after-free and invalid read reports show exactly where the bad access happened and where the memory was allocated.
- The computer slows down significantly under Valgrind because every instruction is checked, but the reports are very precise.
- The syntax is: gcc -g main.c -o app then valgrind --leak-check=full ./app.
- A realistic use: checking a program that allocates linked list nodes to confirm every node is freed.
- A surprising detail: Valgrind reports leaks by default only on exit; use --leak-check=full to see detailed blocks.
- The example program intentionally leaks a heap block so you can see the kind of report Valgrind produces; the fix is shown in the comments.
- Build with -g so Valgrind can show file and line numbers.
- Run with --leak-check=full to see detailed leak reports.
- Fix leaks by freeing every block on every path, including error paths.
- Use Valgrind regularly during development, not just when something crashes.
- Memory discipline is a superpower. You are building it now!
#include <stdio.h>
#include <stdlib.h>
int main(void) {
// Allocate space for one int on the heap
int *p = malloc(sizeof *p);
// Check that the allocation succeeded
if (p == NULL) {
return 1;
}
// Store a value in the block
*p = 42;
// Print the value to show the block is in use
printf("Value: %d\n", *p);
// BUG on purpose: we forget to free p here
// Valgrind will report a leak of 4 bytes at this allocation site
// The fix is to add: free(p);
return 0;
}What happens: Value: 42
Breaking it down
Build with -g
gcc -g main.c -o appIncludes debug symbols so Valgrind can report file names and line numbers. Without -g, the report shows only addresses.
Run under Valgrind
valgrind --leak-check=full ./appRuns the program under Valgrind and prints a summary at the end, including leaks and invalid accesses.
The leak
p = malloc(...); // no freeThe block allocated for p is never freed. Valgrind reports it as 'definitely lost' with the size and the allocation site.
The fix
free(p);Returns the block to the system so it can be reused. After the fix, Valgrind reports 'no leaks'.
Common Valgrind reports
| Report | Meaning | Typical fix |
|---|---|---|
| definitely lost | Block never freed | Add free on all paths |
| invalid read | Read past or after free | Check bounds and lifetime |
| invalid write | Write past or after free | Check bounds and lifetime |
| uninitialised value | Use of uninitialized data | Initialize the variable |
| double free | Freed twice | Free once, set to NULL |
A helpful analogy
Valgrind is like a strict building inspector who follows every worker around and writes a report on every unsafe action. The worker is slower because the inspector is watching, but the report tells you exactly what to fix before an accident happens.
Nesting rules
- 1.Compile with -g for useful reports; Valgrind uses debug symbols to name lines.
- 2.Free every heap block on every return path, including error branches.
- 3.Use --leak-check=full to see detailed leak blocks, not just a summary.
- 4.Run Valgrind on representative inputs so it can exercise the code paths that matter.
Common mistakes
Running Valgrind without -g
Avoid
gcc main.c -o app
valgrind ./appUse instead
gcc -g main.c -o app
valgrind ./appWithout -g, Valgrind cannot show file names and line numbers, so the report is harder to act on.
Ignoring 'still reachable' blocks
Avoid
assume the program is cleanUse instead
review and decide if they matterStill reachable blocks are not leaks at exit but may indicate unintended lifetime. Review them, especially in long-running code.
Freeing memory twice
Avoid
free(p);
free(p);Use instead
free(p);
p = NULL;Double free corrupts the heap and Valgrind reports it. Set p to NULL after free to prevent it.
Quick tips
- •Run Valgrind on your tests before every release.
- •Read the report from top to bottom; the allocation stack shows where to fix.
- •Use --track-origins=yes to see where uninitialized values came from.
- •Try adding free(p); to the example and rerun Valgrind to see the leak disappear.
- •Combine Valgrind with unit tests to exercise many code paths quickly.