Course contentsShow
← C
Lesson 566 of 1,2198. Memory ManagementFree lesson

Reading 'definitely lost' reports

Reading 'definitely lost' reports

What you'll learn: How to identify the exact cause of a memory leak by interpreting the "definitely lost" section of a Valgrind analysis.

The "Definitely Lost" problem

Imagine you are at a library. You check out a book, but then you lose your library card. Even if you want to return the book, you no longer have the record or the "link" to it. In C, a "definitely lost" error occurs when you allocate memory on the heap (using malloc), but then overwrite or lose the pointer that tracks that address before calling free.

At this point, that memory is a ghost. It is sitting in your RAM, unusable by other programs, but your code has no way to find it or release it.

Anatomy of the error

When you run Valgrind, the "Leak Summary" is your starting point. If you see definitely lost, Valgrind has found a block of memory that is unreachable. The tool provides a "stack trace" that tells you exactly where that memory was born.

Consider this leaky code:

#include <stdlib.h>

void create_leak() {
    int *numbers = malloc(10 * sizeof(int));
    
    // Logic happens here...

    // Error: We return without calling free(numbers)
    // Once the function ends, the pointer 'numbers' is destroyed,
    // but the heap memory remains allocated forever.
    return; 
}

int main() {
    create_leak();
    return 0;
}

How to read the report

Valgrind will produce a report that looks something like this:

40 bytes in 1 blocks are definitely lost in loss record 1 of 1
at 0x4C2FB0B: malloc (in /usr/lib/valgrind/vgpreload_memcheck...)
by 0x400537: create_leak (example.c:5)
by 0x400547: main (example.c:13)

To fix this, read the trace from top to bottom:

  1. The top line tells you how much memory was leaked (40 bytes).
  2. The "at" line confirms malloc was the source.
  3. The first "by" line is the "smoking gun." It points to example.c:5.

This doesn't mean line 5 is "wrong"; it means the memory allocated at line 5 was never freed before its pointer went out of scope. To fix a "definitely lost" error, you must ensure that every path out of that function (or every overwrite of that pointer) is preceded by a free().

Key takeaway

A "definitely lost" report points to the line where memory was allocated, reminding you that you failed to provide a corresponding free for that specific pointer.