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

Identifying 'indirectly lost' memory

Identifying 'indirectly lost' memory

What you'll learn: You will understand how "indirectly lost" memory occurs when a parent structure is leaked, causing all of its internal data to become unreachable.

The Suitcase Analogy

Imagine you have a suitcase (a pointer to a struct) and inside that suitcase, you’ve packed several smaller boxes (pointers to other heap-allocated data). If you lose the key to the suitcase or accidentally throw the entire suitcase into the ocean, you haven't just lost the suitcase itself—you’ve lost everything inside it, too.

In Valgrind terms, the suitcase is definitely lost because you lost the direct pointer to it. The boxes inside are indirectly lost. They aren't lost because you forgot to free them specifically; they are lost because the only way to reach them was through the suitcase you already misplaced.

Seeing it in Code

Indirect loss usually happens with complex data structures like linked lists, trees, or structs that contain pointers to other buffers.

#include <stdlib.h>

struct Node {
    int *data;
    struct Node *next;
};

int main() {
    // We allocate the 'suitcase'
    struct Node *node = malloc(sizeof(struct Node));
    
    // We allocate a 'box' inside the suitcase
    node->data = malloc(sizeof(int) * 10);
    node->next = NULL;

    // LEAK: We lose the pointer to the node itself.
    node = NULL; 

    return 0;
}

When you run Valgrind on this code, it will report:

  1. Definitely lost: The memory for the struct Node.
  2. Indirectly lost: The memory for the int array (node->data).

Valgrind distinguishes between these because the fix is almost always found by looking at the "definitely lost" pointer. Once you fix the code to properly free the parent structure, the indirect leaks often vanish along with it.

Why it matters

Focusing on indirect leaks is a common trap for beginners. If your report shows 500 bytes "definitely lost" and 10,000 bytes "indirectly lost," don't panic about the 10,000 bytes. It usually means you leaked one large container (like a root node of a tree) that was holding onto everything else.

By tracing the pointer that was "definitely lost," you automatically regain access to—and the ability to free—all the "indirectly lost" memory nested within it.

Key takeaway

Memory is "indirectly lost" when it is still pointed to by a leaked structure, making it unreachable even though the pointer to that specific memory technically still exists.