Course contentsShow
← C
Lesson 1165 of 1,21916. Practice and ProjectsFree lesson

Installing and running `valgrind`

Installing and running valgrind

What you'll learn: How to install Valgrind and use it to scan your compiled programs for hidden memory errors.

The invisible scout

Imagine you are building a house. To the naked eye, everything looks perfect. But beneath the floorboards, there might be a slow pipe leak that will eventually rot the wood. In C, memory leaks and "out-of-bounds" errors are those hidden leaks. Your program might run fine today, but it’s slowly breaking your computer's memory.

Valgrind is like a professional inspector who follows your program around as it runs. It watches every time you ask for memory (malloc) and every time you give it back (free), reporting exactly where you forgot to clean up.

Getting Valgrind ready

If you are on Linux (like Ubuntu), installing Valgrind is a simple one-line command in your terminal:

sudo apt-get install valgrind

For macOS users, Valgrind can be tricky on newer chips, so many developers use alternative tools or Docker containers to run it. Once installed, you can check if it's ready by typing valgrind --version.

Running your first scan

To use Valgrind, you don't need to change your C code, but you do need to compile it with a special "debug flag" (-g). This flag tells the compiler to keep a record of line numbers so Valgrind can tell you exactly where a mistake happened.

Here is a simple program with a memory leak:

#include <stdlib.h>

int main() {
    // We allocate memory for 10 integers
    int *numbers = malloc(10 * sizeof(int));

    // We use the memory...
    numbers[0] = 42;

    // ERROR: We forgot to call free(numbers)!
    return 0;
}

To find the error, compile and run it like this:

  1. Compile: gcc -g my_program.c -o my_program
  2. Inspect: valgrind ./my_program

Valgrind will run your program and then print a summary. Look for the line that says "LEAK SUMMARY." It will tell you exactly how many bytes were "definitely lost." If you see "All heap blocks were freed -- no leaks are possible," you’ve passed the test!

Key takeaway

Run valgrind ./your_program on code compiled with the -g flag to catch hidden memory leaks before they crash your software.