Skip to content
systemcoding.dev
Debugging

The Complete Guide to Valgrind for C and C++

Find memory errors, leaks, uninitialised reads and thread races in C and C++ with Valgrind, then profile heap and cache use, debug live and gate your CI.

27 min read
Summarize in AI
Flat illustration of a debugger stopped at a breakpoint beside the register values, with the C, C++ and LLVM logos.

A C or C++ program can be wrong in ways the compiler never mentions and the tests never trigger. It reads one byte past a buffer and gets the neighbor's data. It branches on a variable nobody set. It frees a pointer twice and corrupts the allocator, and the crash arrives an hour later in an unrelated function. These bugs share a property: the program often works anyway, on your machine, today. Valgrind is the tool that makes them fail on purpose. It runs your unchanged binary on a software CPU that checks every memory access, and it reports each bad one with the stack that made it and, for heap memory, the stack that allocated or freed the block.

Valgrind needs no rebuild beyond -g, it finds invalid accesses, uninitialised reads, leaks and mismatched frees in the exact binary you give it, and it pays for that with a run many times slower than native.

This guide covers Valgrind 3.24 on Linux 6.12 with GCC 14. It starts with how the tool works and how to run it, goes through every kind of Memcheck error with the report it prints, then covers leaks, uninitialised values, suppressions and options. It then turns to the other tools in the suite, for threads, heap profiling and cache simulation, to debugging a live process, to teaching Memcheck about your own allocator, and to running it all in CI. The closing sections compare it with AddressSanitizer and list the cases where it is the wrong choice. Each topic has a shorter post in this series with one more example, and this guide is the map.

How Valgrind works

Valgrind is a framework, and the tools are plug-ins. When you run valgrind ./app, the core loads your program, translates its machine code, one block at a time, into an intermediate representation, hands that to the tool, which adds its checking code, and then compiles the result back to machine code that runs on the real processor. The program never executes natively. Every instruction of the program and of every library it loads passes through the translator, which is why Valgrind needs no instrumented build and also why it is slow. The design is in the Valgrind user manual.

The default tool is Memcheck, and it is the one most people mean by "Valgrind". It keeps two kinds of shadow state for the whole process. The first records for every byte whether it is addressable: allocated heap, a live stack slot or a mapped region. The second records for every bit whether it is defined: initialized by a write or computed only from defined values. It replaces malloc, free, new and delete with versions that record each block and surround it with red zones, and it holds freed blocks back from reuse for a while so a late use is caught. The other tools in the suite use the same machinery for different questions:

ToolFlagQuestion it answers
Memcheck--tool=memcheck (default)Which memory accesses and frees are invalid, and what leaked?
Helgrind--tool=helgrindWhich accesses race, and are locks taken in a consistent order?
DRD--tool=drdThe same race question, with lower memory use and contention reports
Massif--tool=massifWhich allocation sites hold the heap, and how does it grow over time?
Callgrind--tool=callgrindHow many instructions run in each function, and who calls whom?
Cachegrind--tool=cachegrindHow many instruction and data cache misses does each line cause in a simulated cache?

The price of the approach is run time and memory. The Valgrind quick start says a program runs much slower under it, giving 20 to 30 times as an example, and uses much more memory. The ratio depends on the program, with memory-heavy code at the slow end. So Valgrind belongs in test runs and debugging sessions, on small inputs, and not in production.

Run it for the first time

Compile with debug information and without heavy optimization. -g lets Valgrind print file names and line numbers, and -O0 or -O1 keeps stack traces close to the source, since inlining at -O2 merges frames. Do not strip the binary.

Shell
gcc -g -O0 -Wall -Wextra -o app app.c
valgrind ./app

The simplest useful program is one with an invalid write, so you see what an error looks like:

bad.cc
#include <stdlib.h>

int main(void)
{
    int *a = malloc(4 * sizeof *a);
    a[4] = 1;
    free(a);
    return 0;
}
Text
==3011== Memcheck, a memory error detector
==3011== Copyright (C) 2002-2024, and GNU GPL'd, by Julian Seward et al.
==3011== Using Valgrind-3.24.0 and LibVEX; rerun with -h for copyright info
==3011== Command: ./bad
==3011==
==3011== Invalid write of size 4
==3011==    at 0x10916B: main (bad.c:6)
==3011==  Address 0x4a4a050 is 0 bytes after a block of size 16 alloc'd
==3011==    at 0x4846828: malloc (vg_replace_malloc.c:381)
==3011==    by 0x10915E: main (bad.c:5)
==3011==
==3011== HEAP SUMMARY:
==3011==     in use at exit: 0 bytes in 0 blocks
==3011==   total heap usage: 1 allocs, 1 frees, 16 bytes allocated
==3011==
==3011== All heap blocks were freed -- no leaks are possible
==3011==
==3011== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

Everything between the ==3011== markers is Valgrind talking, and the number is the process id. Read the error from the top. The first line names the class and the size: an invalid write of 4 bytes. The first stack is the access, main at line 6. The second block describes the address in terms of a heap block: it is "0 bytes after a block of size 16" that was allocated at line 5, so the program wrote one element past the end of a four-element array. The ERROR SUMMARY at the bottom is what a script checks. Addresses and ids differ on each run. The error is the same one AddressSanitizer reports as a heap-buffer-overflow.

The catalog of Memcheck errors

Memcheck reports a fixed set of error classes, and recognizing each by its first line saves time. The ones below cover almost everything you will meet.

Invalid read and invalid write

Invalid read of size N and Invalid write of size N mean an access to memory that is not addressable: past the end of a block, before its start, inside a freed block, or on a stack slot below the stack pointer. The "Address ... is" description names the relationship: N bytes after a block of size M alloc'd is an overflow, N bytes before an underflow, and N bytes inside a block of size M free'd a use after free, followed by the stack of the free and of the allocation. These are the errors to fix first, since they can corrupt data.

Conditional jump depends on uninitialised value

Conditional jump or move depends on uninitialised value(s) means a branch, a pointer or a system call argument depended on a value that was never written. It is reported at the use, which may be far from the missing assignment. Add --track-origins=yes to see where the undefined value was created, as a later section shows.

Invalid free and mismatched free

Invalid free() / delete / delete[] / realloc() is a free of an address that is not the start of a live block: a double free, a free of a stack or global address, or a free of the middle of an array. Mismatched free() / delete / delete [] is a block released by the wrong family, such as malloc memory passed to delete, or new[] memory passed to plain delete. Both are undefined behavior, and both are cheap to find here.

mix.cc
#include <stdlib.h>

int main(void)
{
    int *a = malloc(8);
    free(a);
    free(a);
    return 0;
}
Text
==3090== Invalid free() / delete / delete[] / realloc()
==3090==    at 0x484A2B8: free (vg_replace_malloc.c:989)
==3090==    by 0x10917D: main (mix.c:7)
==3090==  Address 0x4a4a040 is 0 bytes inside a block of size 8 free'd
==3090==    at 0x484A2B8: free (vg_replace_malloc.c:989)
==3090==    by 0x109170: main (mix.c:6)
==3090==  Block was alloc'd at
==3090==    at 0x4846828: malloc (vg_replace_malloc.c:381)
==3090==    by 0x10915E: main (mix.c:5)

The report has three stacks: the bad free, the earlier free and the allocation, which is the whole life of the block.

Overlapping memcpy and bad system call arguments

Source and destination overlap in memcpy(...) means memcpy was given overlapping ranges, which the C standard makes undefined, and the fix is memmove. Syscall param write(buf) points to uninitialised byte(s) means bytes you passed to a system call were never initialized, which is how padding in a struct leaks to a file or socket. Syscall param read(buf) points to unaddressable byte(s) means the kernel was told to write into memory you do not own.

Fishy arguments

Argument 'size' of function malloc has a fishy (possibly negative) value: -1 is the sign of a size computation that went negative and wrapped to a huge unsigned number. It is almost always an arithmetic bug upstream, and Valgrind spots it when the value reaches malloc.

Memory leaks

At exit, Memcheck scans memory the way a garbage collector would, starting from registers, stacks and globals, and classifies every block it cannot reach. Ask for the full report with --leak-check=full, and for all the categories with --show-leak-kinds=all:

Shell
valgrind --leak-check=full --show-leak-kinds=all ./app

The four categories are the ones the earlier posts in this series explain in detail.

CategoryMeaningAction
Definitely lostNo pointer to the block existsFix first; the stack shows the allocation
Indirectly lostReachable only through definitely lost blocksClears when the owner is freed
Possibly lostOnly an interior pointer to the block existsInspect the pointer arithmetic
Still reachableA pointer to the start exists at exitUsually harmless; free at shutdown if you want clean runs

A leak report looks like this, with the (N direct, M indirect) text counting the block and everything only it pointed to:

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

Two limits matter. The report is printed only when the program exits normally, so a crash or a kill yields no leak summary. And it finds blocks that are unreachable, not blocks that grow without bound while staying reachable, such as a cache that is never trimmed. For growth over time, use Massif, described below. To fail a test on leaks, use --error-exitcode=1 with --errors-for-leak-kinds=definite,possible, which is how the CI section below uses it.

Uninitialised values and where they come from

Memcheck tracks definedness through copies and arithmetic and complains only when an undefined value affects behavior: a branch, an address, or a system call. That is why the report says "depends on" and not "is". With --track-origins=yes it also records where each undefined value was created and adds a line to the report:

Text
==3200== Conditional jump or move depends on uninitialised value(s)
==3200==    at 0x1091A4: is_slow (uninit.c:17)
==3200==    by 0x1091D2: main (uninit.c:25)
==3200==  Uninitialised value was created by a heap allocation
==3200==    at 0x4846828: malloc (vg_replace_malloc.c:381)
==3200==    by 0x10916E: make_config (uninit.c:10)
==3200==    by 0x1091B3: main (uninit.c:24)

The origin is the block, not the field, so you read the allocating function and check every member it should set. The other origins are a stack allocation, a local never written, and a client request, memory your own code marked undefined. The flag slows the run and uses more memory, so apply it when a plain report is unclear.

The fix pattern in C is to initialize at the source: calloc for heap blocks, designated initializers or = {0} for structs, and memset before writing a struct out as bytes, since padding is not reliably cleared. Whether -O2 or -O0 hides or reveals the bug depends on the compiler, so rely on the tool, not on how the program behaves.

Silencing known issues

A real program links libraries that do odd things on purpose. A suppression file tells Valgrind to skip an error that matches a kind and a call stack. Generate entries instead of writing them by hand:

Shell
valgrind --leak-check=full --gen-suppressions=all ./app 2> vg.log

For each error, the log gets a block like:

Text
{
   libfoo-init-reachable
   Memcheck:Leak
   match-leak-kinds: reachable
   fun:malloc
   obj:/usr/lib/x86_64-linux-gnu/libfoo.so.1.4
   fun:foo_init
   fun:main
}

Paste it into a file, give it a descriptive name, and load it with --suppressions=app.supp. Keep entries narrow. Name the library with obj:, restrict leak entries with match-leak-kinds, keep a frame of your own code in the stack, and never suppress an error whose first frame is yours. Use -v to list which entries matched, and delete the ones that never do. A growing suppression file is a warning that a dependency is in poor shape.

Options you will use every day

Valgrind has many options, and a handful cover most work. They go before the program name.

OptionEffect
--leak-check=fullReport each leak with its allocation stack
--show-leak-kinds=allInclude still-reachable and possibly-lost blocks
--track-origins=yesShow where uninitialised values were created
--error-exitcode=NExit with N if errors were found, for scripts and CI
--num-callers=NNumber of frames per stack, default 12; raise for deep call chains
--log-file=FILEWrite the report to a file; %p is replaced by the process id
--suppressions=FILELoad a suppression file
--gen-suppressions=allPrint a suppression for each error
--trace-children=yesFollow exec into child programs, such as a shell script that starts the program
--fair-sched=yesA fairer thread scheduler, helpful for threaded programs that seem to hang
--main-stacksize=NSize of the main thread's stack, for programs with large locals
--vgdb=yes --vgdb-error=0Stop for a debugger at the first error

Two of them solve common confusion. --trace-children=yes matters when you run a program through a script: without it Valgrind checks the shell and none of your code. And --log-file=vg.%p.log keeps the report apart from the program's own output, which matters when the program prints a lot or when several processes run.

Threads: Helgrind and DRD

Memcheck says nothing about data races. For them use Helgrind or DRD, both of which build a happens-before relation from the POSIX threads calls and report conflicting accesses with no ordering between them. Run the same test with each:

Shell
valgrind --tool=helgrind ./threaded
valgrind --tool=drd ./threaded

A Helgrind race report names both accesses and the locks each side held:

Text
==3310== Possible data race during read of size 8 at 0x10C020 by thread #3
==3310== Locks held: none
==3310==    at 0x10917C: worker (race.c:9)
==3310==
==3310== This conflicts with a previous write of size 8 by thread #2
==3310== Locks held: none
==3310==    at 0x109185: worker (race.c:9)
==3310==
==3310== Address 0x10c020 is 0 bytes inside data symbol "counter"

Locks held: none on both sides says that no lock protects the data, and the fix is one mutex taken by every access. Helgrind also reports lock order ... violated when two threads take the same locks in opposite order, which is a deadlock risk even if this run did not deadlock. DRD uses less memory and has contention reports through --exclusive-threshold, which print each lock held longer than a threshold. Both see only the synchronization they intercept, so custom spinlocks and lock-free code produce false reports unless you annotate them with ANNOTATE_HAPPENS_BEFORE and ANNOTATE_HAPPENS_AFTER. For atomics-heavy code, ThreadSanitizer is the better choice, as the sanitizer guide in this series explains.

Where the heap goes: Massif

A leak check answers "what was never freed". It does not answer "why does the process need 2 GB". Massif is the heap profiler for that question. It takes snapshots of the heap during the run and records which allocation sites account for the memory at each point, including at the peak.

Shell
valgrind --tool=massif --time-unit=B ./app
ms_print massif.out.3400 | head -40

--time-unit=B uses bytes allocated as the time axis instead of instructions, which makes runs comparable across machines and makes the graph easy to read. The output file name carries the process id, and ms_print turns it into a text graph and a table of snapshots. The table has a column for the useful heap, the bytes you asked for, and a column for the extra heap, the allocator's overhead and padding:

Text
--------------------------------------------------------------------------------
  n        time(B)         total(B)   useful-heap(B) extra-heap(B)    stacks(B)
--------------------------------------------------------------------------------
  0              0                0                0             0            0
  1         41,200           41,200           40,000         1,200            0
  2         82,400           82,400           80,000         2,400            0
  3        123,600          123,600          120,000         3,600            0

The numbers above are an illustration of the layout, from a program that allocates 40,000 bytes at a time. The detailed snapshots, marked in the table, show a tree of allocation sites with the share of the heap each holds. Read the peak snapshot first: it names the call chain that owns most of the memory at the worst moment, which is where to look for a smaller data structure or a freed-too-late buffer. The extra-heap column tells you when many small allocations waste space in headers and alignment, in which case a pool or an array of structs beats a list of nodes.

Massif tracks heap blocks only by default. Add --stacks=yes to include the stack, at a large slowdown, and --pages-as-heap=yes to count whole pages mapped by mmap, which catches memory that bypasses malloc. Because Massif measures bytes allocated and not process size, its totals differ from what top shows, and it is the better guide to what your own code requested.

Where the time goes: Callgrind and Cachegrind

Callgrind counts instructions. It records, for every function and every call edge, how many instructions executed, which makes it a profiler that does not depend on timing noise and gives the same result on every run for a deterministic program.

Shell
valgrind --tool=callgrind ./app
callgrind_annotate callgrind.out.3500 | head -20
Text
--------------------------------------------------------------------------------
Profile data file 'callgrind.out.3500' (creator: callgrind-3.24.0)
--------------------------------------------------------------------------------
Events recorded: Ir
Events shown:    Ir
Event sort order: Ir
Thresholds:      99

         Ir  file:function
--------------------------------------------------------------------------------
 52,300,114  /home/dev/app.c:hash_key [/home/dev/app]
 18,442,077  /home/dev/app.c:table_insert [/home/dev/app]
  4,210,890  /home/dev/app.c:main [/home/dev/app]

Ir is "instructions read", the instruction count. The numbers shown are illustrative. The sorted list says that hash_key runs most of the instructions, so it is the function to look at, and a graphical viewer such as KCachegrind shows the call graph with the same data. Callgrind counts instructions and not seconds, so a function with few instructions that waits on memory is under-reported. That is the gap Cachegrind fills.

Cachegrind simulates a CPU's instruction and data caches and counts misses per line:

Shell
valgrind --tool=cachegrind ./app
cg_annotate cachegrind.out.3600
Text
==3600== I   refs:      1,234,567
==3600== I1  misses:        1,234
==3600== LLi misses:        1,100
==3600== I1  miss rate:      0.10%
==3600== D   refs:        500,000  (350,000 rd + 150,000 wr)
==3600== D1  misses:        8,000  (  6,000 rd +   2,000 wr)
==3600== LLd misses:        2,500  (  1,800 rd +     700 wr)
==3600== D1  miss rate:       1.6%

These figures are an example of the format, not a measurement. Cachegrind's model is a simplified cache of the kind of machine it detects, so treat its numbers as a guide to which loops miss, not as a prediction of real timing. Both tools run the program many times slower, so use small inputs. Callgrind's --dump-instr=yes records per-instruction costs for assembly-level reading. These two tools are covered in their own posts in the performance topic of this site, and in this guide they are here so you know the suite has them.

Debug a live program: vgdb

When a report is not enough, you want to stop at the error and look around. Valgrind includes a gdbserver for that, and vgdb connects GDB to it:

Shell
valgrind --vgdb=yes --vgdb-error=0 ./app

Valgrind then prints the command to run in a second terminal:

Text
==3700== TO DEBUG THIS PROCESS USING GDB: start GDB like this
==3700==   /path/to/gdb ./app
==3700== and then give GDB the following command
==3700==   target remote | /usr/bin/vgdb --pid=3700

In GDB, target remote | vgdb, then continue. Execution stops at the first Memcheck error, with all variables and frames available, and the full set of GDB commands works. The extra commands are the monitor family, which talk to Memcheck: monitor leak_check full reachable any runs a leak check now, without waiting for exit, monitor who_points_at ADDR lists the pointers to a block, and monitor get_vbits ADDR LEN shows which bits of a range are undefined. For a long-running server, taking two leak snapshots with a batch of requests in between finds a per-request leak without ever stopping the process. The dedicated post on vgdb has the full session.

Teach Memcheck about your own allocator

Memcheck knows malloc because it replaces it. If your program carves objects out of an arena or a pool, Memcheck sees one large block, and an overflow between two objects of the arena is inside a valid block and not reported. Client requests, macros from <valgrind/memcheck.h>, tell Memcheck what your allocator does:

c
#include <valgrind/memcheck.h>

VALGRIND_CREATE_MEMPOOL(arena, 16, 0);
VALGRIND_MEMPOOL_ALLOC(arena, ptr, size);
VALGRIND_MEMPOOL_FREE(arena, ptr);
VALGRIND_DESTROY_MEMPOOL(arena);

For an allocator that frees blocks one at a time, VALGRIND_MALLOCLIKE_BLOCK(ptr, size, redzone, is_zeroed) and VALGRIND_FREELIKE_BLOCK(ptr, redzone) do the same. Mark the backing buffer VALGRIND_MAKE_MEM_NOACCESS first, so only handed-out memory is usable. The macros compile to no-ops on a real CPU, so they can stay in production code, or be wrapped in a header and removed with a build flag. The post on custom allocators walks through an arena example with the report before and after.

Make it a merge gate

A Valgrind run you remember to do is a Valgrind run that happens twice a year. Put it in CI, on the unit tests, with an exit code that means something:

Shell
valgrind --error-exitcode=99 --leak-check=full \
    --errors-for-leak-kinds=definite,possible \
    --track-origins=yes --suppressions=ci/valgrind.supp \
    --log-file=valgrind-%p.log \
    ./build-vg/tests/unit_tests

--error-exitcode=99 replaces the program's exit status with 99 if Memcheck reported any error, and passes the program's own status through otherwise, so a failing test and a memory error both fail the job. Count definite and possible leaks as errors and ignore still-reachable blocks. Build the tests with -g -O1. Keep the log as an artifact on every run, uploaded even on failure, since the terminal scrolls away. Four practices keep the gate honest. Start from a green main branch, so the gate is never red on day one. Review suppression changes like code. Pin the Valgrind version, and upgrade it in its own pull request. And run only unit tests, sharded if needed, with a job timeout, because a run many times slower than native cannot cover a large integration suite. The earlier post on the merge gate has the workflow file.

A full session on a realistic program

Small examples show the format. A realistic session shows the order of work. Here is a short C program that reads a list of words, counts them in a table and prints the result. It has three real bugs, the kind that survive review:

words.cc
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct entry {
    char *word;
    int   count;
};

static struct entry *table;
static int           used;

static struct entry *find(const char *w)
{
    for (int i = 0; i < used; i++)
        if (strcmp(table[i].word, w) == 0)
            return &table[i];
    return NULL;
}

static void add(const char *w)
{
    struct entry *e = find(w);
    if (e) {
        e->count++;
        return;
    }
    table = realloc(table, (used + 1) * sizeof *table);
    table[used].word = malloc(strlen(w));
    strcpy(table[used].word, w);
    used++;
}

int main(void)
{
    const char *input[] = { "apple", "pear", "apple", "fig" };
    for (int i = 0; i < 4; i++)
        add(input[i]);
    for (int i = 0; i < used; i++)
        printf("%s %d\n", table[i].word, table[i].count);
    free(table);
    return 0;
}

Compile it with gcc -g -O0 -o words words.c and run valgrind --leak-check=full --track-origins=yes ./words. The output is long, so read it in the order of the fix list. The first errors are invalid writes:

Text
==4001== Invalid write of size 1
==4001==    at 0x4850A6E: strcpy (vg_replace_strmem.c:512)
==4001==    by 0x1092B1: add (words.c:29)
==4001==    by 0x109341: main (words.c:36)
==4001==  Address 0x4a4a0a5 is 0 bytes after a block of size 5 alloc'd
==4001==    at 0x4846828: malloc (vg_replace_malloc.c:381)
==4001==    by 0x109296: add (words.c:28)
==4001==    by 0x109341: main (words.c:36)

The block has size 5 and the word apple needs six bytes with its terminator. The bug is malloc(strlen(w)) without the + 1, and strdup would be the idiom that avoids it. Fix it, rerun, and the next error is an uninitialised read:

Text
==4020== Conditional jump or move depends on uninitialised value(s)
==4020==    at 0x1092E5: main (words.c:39)
==4020==  Uninitialised value was created by a heap allocation
==4020==    at 0x484B8B0: realloc (vg_replace_malloc.c:1437)
==4020==    by 0x10927B: add (words.c:27)

The printed count was never set, because the new entry is created by realloc, which does not clear memory, and the code assigns word but not count. The origin points at the realloc, which is where the block that holds the entry came from. Set table[used].count = 1 when you add an entry. Rerun once more:

Text
==4040== HEAP SUMMARY:
==4040==     in use at exit: 15 bytes in 3 blocks
==4040==
==4040== 15 bytes in 3 blocks are definitely lost in loss record 1 of 1
==4040==    at 0x4846828: malloc (vg_replace_malloc.c:381)
==4040==    by 0x109296: add (words.c:28)
==4040==    by 0x109341: main (words.c:36)

Now the memory errors are gone and the leak shows: the program freed the table but not the strings it points to. The three blocks hold apple, pear and fig with their terminators, 6 plus 5 plus 4 bytes. The fix is a loop that frees each word before freeing table. After it, the summary reads All heap blocks were freed -- no leaks are possible.

Notice the order. The invalid write came first because it can corrupt the allocator, which would turn every later report into noise. The uninitialised read came second, since its stack pointed at a block allocation that changed once the first fix altered sizes. The leak came last, and only after the errors were gone could the count be trusted. This is the workflow in miniature: fix, rerun, and let each report show the next one.

C++ specifics

Everything above applies to C++, and a few things change.

Demangled names. Valgrind demangles C++ symbols by default, so stacks show std::vector<int>::push_back(int const&) and not _ZNSt6vectorIiSaIiEE9push_backERKi. If a stack still shows mangled names, add --demangle=yes.

Containers and the standard library. libstdc++ keeps some memory in internal pools until exit. Old versions used an emergency pool and caches that appeared as "still reachable" blocks from std:: frames. Recent libstdc++ releases honor GLIBCXX_FORCE_NEW=1 in the environment, which makes the allocator use new and delete directly so every block is tracked exactly. Set it for leak runs when the library's own caching confuses the report.

Mismatched deallocation. new with free, new[] with delete, and malloc with delete are reported as Mismatched free() / delete / delete [], with the allocation and the wrong release. Smart pointers and containers avoid the whole class, as the earlier post on pairing explains.

Exceptions. A throw unwinds the stack and runs destructors. A leak on an exception path appears only if a test throws, so include tests that make the code throw. A constructor that throws after allocating a raw pointer leaks that pointer, which is the classic reason to hold resources in objects of their own.

**Virtual calls and vptr.** A call through a deleted or uninitialised object shows as an invalid read inside a vtable load, with a stack that ends in the call site. Read the free stack to see where the object died.

Running Valgrind in awkward places

Some environments need extra care.

  • Containers. Valgrind works inside a container. A slim image may lack debug symbols for libc, which gives noisy ??? frames in system code; install the libc debug package or use a suppression file. The host kernel limits, such as address space size, apply.

  • Scripts that start the program. Use --trace-children=yes, or call the binary directly, otherwise Valgrind checks only the shell.

  • Large programs. Memcheck uses additional memory for its shadow state, so a process that is close to a memory limit natively may not fit. Reduce the input or use --max-stackframe and --main-stacksize when a deep recursion fails with a stack message from Valgrind.

  • Cross-architecture. Valgrind runs on the architecture it was built for, with support for x86-64, ARM64 and several others on Linux. It cannot run a program for a different architecture, so test an ARM binary on an ARM machine, or in an emulator at a much larger slowdown.

  • Optimization level. -O2 and -O3 code is valid input, but the reports are harder to read. Inlined frames disappear and line numbers jump. Debug with -O1, and run the optimized build once to confirm that the optimizer did not turn a latent bug into a visible one.

  • Library versions. Valgrind intercepts malloc by symbol name, which works with glibc and with most allocators loaded dynamically. For a statically linked or custom allocator, use the client requests described earlier.

When the program crashes under Valgrind

A program that segfaults under Valgrind is reported in Valgrind's words, and the report is useful because it shows the state at the fault with Memcheck's extra knowledge:

Text
==5001== Process terminating with default action of signal 11 (SIGSEGV)
==5001==  Access not within mapped region at address 0x0
==5001==    at 0x10914A: main (null.c:5)
==5001==  If you believe this happened as a result of a stack
==5001==  overflow in your program's main thread (unlikely but
==5001==  possible), you can try to increase the size of the
==5001==  main thread stack using the --main-stacksize= flag.
==5001==  The main thread stack size used in this run was 8388608.

The text about stack overflow is a standing hint, printed for every SIGSEGV, and you can ignore it unless the fault address is near the stack and the recursion is deep. The address 0x0 says a null pointer. For a read through a wild pointer, an earlier line may say Invalid read of size 4 with Address 0x... is not stack'd, malloc'd or (recently) free'd, which means the address belongs to nothing the program ever owned. Compare that with is 8 bytes inside a block of size 16 free'd, which names a block and its history. The wording tells you whether the pointer is garbage or stale.

Valgrind also prints a few messages that look like errors and are not. Warning: set address range perms: large range appears when a program maps a very large region and is informational. Warning: client switching stacks? appears for code that changes stacks, and means Memcheck's stack tracking may produce false reports there. Warning: ignored attempt to set SIGKILL handler is a program trying something the kernel forbids anyway. Read them once to decide whether they affect your run, then silence the noise with -q for a quiet run when you only care about errors.

The exit code deserves a mention. Valgrind passes the program's exit code through unless you set --error-exitcode, and a program killed by a signal makes Valgrind exit with a status of 128 plus the signal number from the shell's point of view. In scripts, test for both cases, so that a crash under Valgrind is not mistaken for a pass.

Output formats and tool integration

The text report is for people. For a pipeline, Valgrind can write the same findings as XML, which editors, CI dashboards and test harnesses parse:

Shell
valgrind --xml=yes --xml-file=memcheck.xml --leak-check=full ./app

The file lists each error with its kind, its stack frames and the source file and line of each frame, in a documented structure that stays stable between releases. A small script can turn it into annotations on a pull request, so a reviewer sees the invalid write beside the line that caused it and not in a build log. Keep the XML as an artifact, together with the plain log, because the log has the context lines that XML omits.

Most editors and IDEs have a Valgrind view that reads this format, and test runners such as CTest can run a test under Valgrind through the MemoryCheckCommand setting and report the memory results with ctest -T memcheck. The advantage of the built-in route is that the tests, the paths and the options are declared once in the build system. The advantage of a plain script is that you control the options, so choose whichever your team will actually keep running.

Finally, record the Valgrind version and the options used in the job output. A result is only comparable to the next one if both ran the same tool with the same settings, and a new release can report issues that an old one missed. When a report changes after an upgrade, read it as a finding about your code first, and only then as a question about the tool.

Valgrind or AddressSanitizer

Both tools find the memory bugs that crash C and C++ later, and they are complementary. AddressSanitizer is compiled into the program and its documented typical slowdown is 2x, so it fits every test run. Valgrind runs the unmodified binary, with the slowdown described earlier.

Bug or situationMemcheckAddressSanitizer
Heap overflow, use after free, double freeYesYes
Stack buffer overflowNot reliablyYes
Global buffer overflowNoYes
Uninitialised readsYesNo (needs MemorySanitizer)
LeaksYes, with four categoriesYes, through LeakSanitizer
Binary you cannot rebuildYesNo
Speed in a normal test runSlowFast

The practical split: use AddressSanitizer with UndefinedBehaviorSanitizer by default in development and CI, because it is fast and finds stack and global overflows. Add Valgrind for uninitialised reads and for binaries and libraries that you cannot recompile. Never put both in one binary, since both replace the allocator. The dedicated comparison post lists the details.

What Valgrind cannot do

Knowing the limits saves a wasted afternoon.

  • Stack and global overflows. Memcheck sees machine instructions and not variable layout, so an overflow of a local array that stays inside the stack frame passes. Use AddressSanitizer.

  • Memory that stays reachable. A cache that grows forever is not a leak by Memcheck's definition. Use Massif, or compare monitor leak_check snapshots.

  • Programs that do not exit. Leak reports come at exit. For servers, use vgdb snapshots or a test hook that shuts down cleanly.

  • Unsupported instructions. Valgrind translates instructions it knows. New vector instruction sets may be missing in a given release, and a program that requires them fails with an illegal instruction message. Check the release notes for your version, and compile the test build for a baseline instruction set.

  • Programs that switch stacks or allocate memory by themselves. Coroutine libraries, custom mmap allocators and JIT compilers confuse the stack and heap models. Use client requests such as VALGRIND_STACK_REGISTER, or test those parts another way.

  • Statically linked allocators. If the program ships its own malloc or links one statically, Valgrind cannot replace it, and Memcheck sees only the system calls underneath.

  • Speed. Many tests that run in seconds natively take minutes. Choose small inputs and shard.

A workflow that works

Put the pieces in an order you can repeat.

  1. Compile for the check. Debug build, -g -O1, a separate build directory, no stripping.

  2. Run Memcheck with the useful defaults: --leak-check=full --track-origins=yes --error-exitcode=1 --log-file=vg.%p.log.

  3. Fix invalid reads and writes first, then invalid frees, then uninitialised values, then definite leaks. Memory errors corrupt data, so they come before leaks.

  4. Rerun after every fix. Errors hide behind other errors, and a leak report can change shape when a free is added.

  5. Suppress only what is not yours, with narrow entries and a comment that names the library and version.

  6. Move the passing configuration into CI with an exit code, and keep the logs.

  7. Use the other tools when the question changes: Helgrind for races, Massif for growth, Callgrind for time, vgdb when a report needs a debugger.

  8. Add AddressSanitizer in a second job for the bugs Memcheck cannot see.

A last piece of advice about testing coverage: Valgrind checks what the program does, not what it could do. Run the error paths, the empty input, the oversized input and the failed allocation, because each unexecuted branch is a place where a leak or an invalid access can hide. A fuzzer feeding the code under a sanitizer finds many of them without your writing the cases.

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.