Skip to content
systemcoding.dev
Debugging

Find Memory Leaks With Valgrind Memcheck

Run a C program under Valgrind Memcheck with --leak-check=full to find memory that was allocated and never freed, and read the report down to the source line.

7 min read
Summarize in AI
Flat illustration of heap memory as allocated and free blocks, with the C, Rust and Zig logos.

A memory leak is memory a program allocated with malloc and then lost track of without calling free. A short-lived tool can leak for its whole life without anyone noticing. A server that leaks 200 bytes per request exhausts memory after a few million requests and dies at the worst moment. Valgrind Memcheck finds these leaks without recompiling your code: you run the program under it, and at exit it lists every block that was never freed, with the call stack that allocated it. This post shows how to run it with Valgrind 3.24 on Linux 6.12 against a small C program, how to read the report, and how to fix the bug it points to. The next post explains the four leak categories in detail, and the cornerstone guide to Valgrind puts all the tools in context.

How Memcheck works

Valgrind is a framework that runs your program on a synthetic CPU. It translates the machine code of the program and every library it uses into an intermediate form, adds checking instructions, and runs the result. Memcheck is the default tool and the one that tracks memory. It replaces malloc, free and related functions with its own versions, which record every block, and it shadows every byte of memory with flags that say whether the byte is allocated and whether its value is defined. The Memcheck manual describes the design.

The cost is speed. Programs run many times slower under Memcheck, and use more memory, so you use it in test runs, not production. The benefit is that you do not need special builds. Compile with -g so the report has file names and line numbers, and with -O0 or -O1 so the stack traces stay close to the source.

A program that leaks

leak.cc
#include <stdlib.h>

struct node {
    int          value;
    struct node *next;
};

static struct node *push(struct node *head, int value)
{
    struct node *n = malloc(sizeof *n);
    n->value = value;
    n->next = head;
    return n;
}

int main(void)
{
    struct node *list = NULL;
    list = push(list, 1);
    list = push(list, 2);

    list = NULL;
    return 0;
}

The program builds a two-node list and then throws away the only pointer to it by assigning NULL. Nothing calls free. Compile and run under Valgrind:

Shell
gcc -g -O0 -o leak leak.c
valgrind --leak-check=full ./leak

--leak-check=full asks for a stack trace for each leaked block. Without it, Memcheck only prints a count.

Text
==4127== Memcheck, a memory error detector
==4127== Copyright (C) 2002-2024, and GNU GPL'd, by Julian Seward et al.
==4127== Using Valgrind-3.24.0 and LibVEX; rerun with -h for copyright info
==4127== Command: ./leak
==4127==
==4127==
==4127== HEAP SUMMARY:
==4127==     in use at exit: 32 bytes in 2 blocks
==4127==   total heap usage: 2 allocs, 0 frees, 32 bytes allocated
==4127==
==4127== 32 (16 direct, 16 indirect) bytes in 1 blocks are definitely lost in loss record 1 of 1
==4127==    at 0x4846828: malloc (vg_replace_malloc.c:381)
==4127==    by 0x10916E: push (leak.c:10)
==4127==    by 0x1091B9: main (leak.c:22)
==4127==
==4127== LEAK SUMMARY:
==4127==    definitely lost: 16 bytes in 1 blocks
==4127==    indirectly lost: 16 bytes in 1 blocks
==4127==      possibly lost: 0 bytes in 0 blocks
==4127==    still reachable: 0 bytes in 0 blocks
==4127==         suppressed: 0 bytes in 0 blocks
==4127==
==4127== For lists of detected and suppressed errors, rerun with: -s
==4127== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

The number between == markers is the process id, and the addresses will differ on your machine. The structure is the same every time.

Reading the report

Start from the bottom. ERROR SUMMARY: 0 errors is misleading here, because leaks are not counted as errors unless you ask. The LEAK SUMMARY is what matters: 16 bytes are definitely lost, and 16 more are indirectly lost.

The HEAP SUMMARY says that 2 blocks were allocated and none freed, totaling 32 bytes. Those two numbers alone tell you that the program is missing free calls, before you read any detail.

The loss record explains one leak:

Text
32 (16 direct, 16 indirect) bytes in 1 blocks are definitely lost in loss record 1 of 1
   at 0x4846828: malloc (vg_replace_malloc.c:381)
   by 0x10916E: push (leak.c:10)
   by 0x1091B9: main (leak.c:22)

"Definitely lost" means no pointer to the block exists anywhere in the program at exit. The "direct" 16 bytes is the block itself, the first node. The "indirect" 16 bytes is memory reachable only through that lost block: the second node, which the first node pointed to. The stack trace shows where the direct block was allocated, push called from main at line 22, the second push. That block is the head of the list, and when its pointer vanished it took the other node with it. So fixing the head fixes both.

Read the stack from the top: malloc is Valgrind's replacement, and the first frame in your code (push, line 10) is the allocation site.

Fix the leak

Free the list before dropping the pointer. A loop that walks and frees each node does it:

c
static void free_list(struct node *head)
{
    while (head != NULL) {
        struct node *next = head->next;
        free(head);
        head = next;
    }
}

Replace the line list = NULL; in main with free_list(list);. Saving next before the free matters: reading head->next after freeing head is a use-after-free that Memcheck would report as an invalid read. Run again:

Text
==4180== HEAP SUMMARY:
==4180==     in use at exit: 0 bytes in 0 blocks
==4180==   total heap usage: 2 allocs, 2 frees, 32 bytes allocated
==4180==
==4180== All heap blocks were freed -- no leaks are possible
==4180==
==4180== For lists of detected and suppressed errors, rerun with: -s
==4180== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

All heap blocks were freed -- no leaks are possible is the line you want in a clean run.

Options that make the output more useful

The default of --leak-check=full hides one category, and a few more flags are worth knowing.

FlagWhat it does
--leak-check=fullShows each leak with its allocation stack
--show-leak-kinds=allAlso lists "still reachable" and "possibly lost" blocks, which the default hides
--errors-for-leak-kinds=definiteDecides which kinds count as errors, which sets the exit status in tests
--error-exitcode=1Makes Valgrind exit with that code if it found errors, so a test run fails
--num-callers=20Records more frames per stack, helpful in deep call chains
--log-file=vg.%p.logWrites the report to a file named with the pid, so program output stays clean

For an automated check, valgrind --leak-check=full --error-exitcode=1 ./leak exits with 1 when there is a definite leak, and 0 otherwise. A later post covers wiring that into continuous integration.

A leak versus a growing cache

Not everything reported as lost is a bug, and not every bug is reported. A program that appends to a global list for its whole life and frees it at exit shows no leak, because the pointer is still reachable at exit, yet it can still use unbounded memory while running. Memcheck reports leaks only at exit, and only for memory that is no longer pointed to. So a leak check cannot find growth in a long-running process whose data stays reachable. For that you need the heap profiler Massif, covered in the Valgrind guide, or a memory view of the process over time.

Also note that the check happens when the program finishes normally. If the program crashes or is killed, you get no leak summary. A server that never exits needs a shutdown path for tests, or a signal handler that exits cleanly, so that Memcheck gets its chance to run the report.

Leaks on error paths

Most leaks that survive review hide on error paths. A function allocates two buffers, the second malloc fails or a later check rejects the input, and the function returns early without freeing the first. The happy path is clean, so a test that only feeds valid input shows nothing. Memcheck only reports what a run actually did, so to find these leaks you must run the failing cases: bad arguments, a missing file, a rejected packet. A short test list with one invalid input per function, run under valgrind --error-exitcode=1, catches most of them.

A pattern that prevents the bug in C is a single cleanup label at the end of the function. Every early exit jumps to it with goto cleanup, and the label frees each resource, with pointers initialized to NULL at the top so freeing an unallocated one is a harmless free(NULL). The code reads awkwardly to people trained against goto, yet it is the standard idiom in the Linux kernel and many C libraries, because the cleanup lives in one place and cannot drift out of step with the allocations above it.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.