Running a program under Valgrind
What you'll learn: How to use the Valgrind tool to detect hidden memory leaks and errors in your compiled C programs.
The X-Ray for your code
Up to this point, you have likely encountered "Segmentation Faults"—crashes that happen when your program touches memory it shouldn't. However, the most dangerous bugs are the ones that don't crash your program immediately, like a small memory leak that slowly drains your computer's resources.
Think of Valgrind as an X-ray machine. When you run your program normally, you only see the external behavior. When you run it under Valgrind, the tool watches every single byte your program requests from the heap and every single byte it gives back.
How to use it
To use Valgrind, you first compile your code with the -g flag. This flag includes "debugging information," which allows Valgrind to tell you exactly which line of code is causing a problem.
// Save as example.c
#include <stdlib.h>
int main() {
// We allocate space for 10 integers
int *numbers = malloc(10 * sizeof(int));
// We use the memory...
numbers[0] = 42;
// OOPS: We forgot to call free(numbers)!
return 0;
}
Once compiled, you run Valgrind by prefixing your usual execution command:
- Compile:
gcc -g example.c -o my_program - Run:
valgrind ./my_program
Reading the report
When you run the command above, Valgrind will wrap your program and output a report to the terminal. If you have a leak, you will see a "Heap Summary" at the bottom. It might say:
definitely lost: 40 bytes in 1 blocks
Because we used the -g flag during compilation, Valgrind will even point to the specific malloc line where that "lost" memory was originally born.
Valgrind doesn't just find leaks; it also catches "Invalid writes" (trying to store data past the end of an array) and "Use of uninitialized values." It is your best friend for ensuring your program isn't just working by accident, but is truly memory-safe.
Key takeaway
Run valgrind ./your_program to track down memory leaks and illegal memory access that standard testing might miss.