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

Reading the Valgrind leak summary

Reading the Valgrind leak summary

What you'll learn: How to interpret the "Leak Summary" table to distinguish between accidental oversights and critical memory errors.

After you run your program through Valgrind, the tool provides a final report at the very bottom of the terminal output. This is the Leak Summary. It acts like a bank statement for your computer’s RAM, telling you exactly how much memory you "withdrew" (allocated) versus how much you "deposited" (freed) back into the system.

The four categories of leaks

Valgrind categorizes leaks based on whether the program still has a pointer pointing to that memory when the program finishes.

  • Definitely lost: This is your biggest priority. It means you have no pointer left that knows where this memory is. It’s like losing a luggage claim ticket; the suitcase is still at the airport, but you have no way to prove it’s yours or ask for it back. You must fix these.
  • Indirectly lost: This happens with nested structures (like a linked list). If you lose the pointer to the "head" node, all the nodes following it are "indirectly" lost. Fix the parent pointer, and these often vanish.
  • Possibly lost: Valgrind sees a pointer, but it’s not pointing to the start of the memory block. This usually happens with complex pointer arithmetic.
  • Still reachable: This memory was never freed, but the program still had a valid pointer to it when it exited. While technically a "leak," it’s often considered minor because the Operating System reclaims this memory anyway once the process ends. However, in professional C coding, we strive for a "clean" Valgrind report with 0 bytes still reachable.

Seeing it in action

Consider this snippet where we forget to clean up:

#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 exit without calling free(numbers)
    return 0;
}

If you run this, Valgrind will report: definitely lost: 40 bytes in 1 blocks

This tells you exactly what to look for: one malloc call that was never paired with a free.

Why it matters

A few bytes "still reachable" won't crash your computer. However, "definitely lost" memory inside a loop is a ticking time bomb. It creates a memory leak that slowly consumes all available RAM until your program—or the entire system—crashes. By reading the summary, you can instantly tell if your program is "leaking" or just "untidy."

Key takeaway

Focus on fixing "definitely lost" memory first, as these represent memory addresses your program has completely forgotten how to access.