Table of Contents

Valgrind Basics

Valgrind instruments your program to observe every memory access and instruction execution. Install via your package manager, compile with debug symbols, then run with valgrind.

sudo apt install valgrind                  # Debian/Ubuntu
sudo dnf install valgrind                  # Fedora/RHEL

Compilation flags are crucial for Valgrind to provide accurate reports:

gcc -g -O0 -o program program.c            # correct: debug symbols, no optimization
gcc -O3 -g -o program program.c            # wrong for memcheck: O3 can confuse line attribution

-g includes DWARF debug symbols so Valgrind can map machine addresses back to source lines and function names. -O0 disables optimization; Valgrind strongly recommends -O0 for memcheck runs because optimizations can reorder, merge, or eliminate memory accesses in ways that make Valgrind's line-number attribution imprecise.

For other Valgrind tools (profiling), -O2 or -O3 is acceptable; only memcheck's error reporting is affected by optimization.

Running Valgrind:

valgrind ./program              # run with default tool (memcheck)
valgrind --tool=memcheck ./program         # explicit tool selection
valgrind --tool=helgrind ./program         # use helgrind for threading bugs

The default tool is memcheck, used for memory error detection. Other tools (helgrind, callgrind, cachegrind, massif) are selected with --tool=name.

Common options:

valgrind --leak-check=full --show-leak-kinds=all ./program

--leak-check=full reports all types of leaks; --show-leak-kinds=all includes “possibly lost” and “still reachable” blocks. See Valgrind memcheck for leak checking details.

Output and logging:

valgrind --log-file=valgrind.log ./program    # write output to file
valgrind -v ./program                         # verbose (more detail)
valgrind -q ./program                         # quiet (less output)

By default, Valgrind prints to stderr. For long runs or batch jobs, redirect to a file with --log-file. -v shows more internal details; -q suppresses summary information.

Suppressions: Valgrind can produce false positives from system libraries or language runtimes. Use --suppressions=file.supp to ignore known benign errors. See Valgrind Suppressions for details.

Performance: Valgrind runs 10-50x slower than native execution. For quick test runs and debugging, this is fine. For production profiling, use perf instead. Valgrind is best used in your test suite—set it up to run automatically on small test cases, not on massive simulations.