Skip to content
Tutorials Center
My learning

Topics

C Reference ยท Concepts and Tools

Valgrind for C programs

Reference for Valgrind Memcheck: run a C program under it, read reports for invalid reads, uninitialized values and leaks, and know its limits compared to sanitizers.

Valgrind is a tool that runs your compiled program on a virtual CPU and watches every memory access. Its default tool, Memcheck, finds invalid reads and writes, use of uninitialized values, bad free calls and memory leaks. You do not have to recompile: you run valgrind ./program instead of ./program. It runs on Linux (and some other Unix systems); on macOS support is limited, and Windows programs need other tools such as Dr. Memory or AddressSanitizer.

Valgrind is slow (programs usually run 10 to 50 times slower), but it catches bugs that a normal run hides, and it works on binaries whose source or build flags you cannot change.

Valgrind needs a normal Linux shell, so the commands and reports here are read-only. The one runnable example counts allocations and frees with a small wrapper, which is the bookkeeping that a leak report is built on.

Running it

Compile with debug information and without optimization so reports show source lines, then run under Memcheck:

TEXT
gcc -std=c23 -g -O0 program.c -o program
valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes ./program
Option Effect
--leak-check=full list each leaked block with the call stack of its allocation
--show-leak-kinds=all include "still reachable" and "possibly lost" blocks
--track-origins=yes for uninitialized-value errors, show where the value came from (slower)
--error-exitcode=1 make the exit status non-zero when errors are found (useful in CI)
--log-file=out.txt write the report to a file
--suppressions=file hide known false positives from system libraries

Reading a report

A read-only program with three common mistakes:

C
#include <stdlib.h>
#include <string.h>

int main(void) {
    char *a = malloc(4);
    a[4] = 'x';                    /* invalid write: one byte past the block */
    int flag;
    if (flag) {                    /* conditional jump on an uninitialized value */
        a[0] = 'y';
    }
    char *b = malloc(100);
    memset(b, 0, 100);
    return 0;                      /* a and b are never freed */
}

The report contains entries like these (addresses and counts shortened):

TEXT
Invalid write of size 1
   at 0x...: main (program.c:6)
 Address 0x... is 0 bytes after a block of size 4 alloc'd
   at 0x...: malloc (vg_replace_malloc.c:...)
   by 0x...: main (program.c:5)

Conditional jump or move depends on uninitialised value(s)
   at 0x...: main (program.c:8)
 Uninitialised value was created by a stack allocation
   at 0x...: main (program.c:3)

HEAP SUMMARY:
    in use at exit: 104 bytes in 2 blocks
  total heap usage: 2 allocs, 0 frees, 104 bytes allocated

LEAK SUMMARY:
   definitely lost: 104 bytes in 2 blocks

Each error shows the access, the stack at the moment of the error, and, for heap blocks, where the block was allocated or freed.

Leak categories

  • definitely lost: no pointer to the block exists any more. This is a real leak.
  • indirectly lost: reachable only through a definitely lost block (for example the nodes of a lost list).
  • possibly lost: only an interior pointer to the block remains. Usually a leak.
  • still reachable: a pointer exists at exit (a global, for example) but the block was never freed. Harmless in short programs, but a leak in long-running ones.
  • suppressed: matched a suppression rule.

Try it

C Counting allocations: the idea behind a leak report

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Usage notes

  • Fix the first error first. Later reports are often consequences of an earlier invalid access.
  • Valgrind sees only what runs. A leak or overflow in code that your test never reaches is not reported. Exercise error paths too.
  • It cannot see stack and global array overflows well: Memcheck tracks heap blocks and uninitialized values precisely, but a write past a local or global array may go unnoticed. AddressSanitizer is better at those (see Sanitizers).
  • Do not combine it with ASan. Run them in separate builds.
  • Other tools in the suite: --tool=helgrind and --tool=drd find thread data races and lock misuse, --tool=massif profiles heap usage over time, --tool=callgrind profiles function calls (view with kcachegrind).
  • False positives can appear from optimized code or system libraries; use debug builds and suppression files.
  • Exit status. By default Valgrind returns your program's exit status, so use --error-exitcode in automated tests.