Valgrind Guide
sudo apt install valgrind brew install valgrind # Windows: use Dr.Memory or WSL
Valgrind runs your program in a virtual machine (dynamic binary instrumentation), detecting memory leaks, invalid reads/writes, use-after-free, and double frees. The default Memcheck tool is the gold standard for C/C++ memory safety.
Beyond Memcheck, Valgrind includes: Cachegrind (cache profiling), Callgrind (call-graph profiling with `callgrind_annotate`), Helgrind (thread race detection), Massif (heap profiler), and DHAT (heap allocation analysis).
Expect a 5-20x slowdown under Valgrind: use it for debugging, not production. Run with `--tool=memcheck --leak-check=full`. GUI alternatives: AddressSanitizer (ASan) for faster runs, Heaptrack for KDE-integrated heap analysis.
Memcheck
valgrind --leak-check=full --show-leak-kinds=all ./myapp valgrind --leak-check=full --track-origins=yes ./myapp # Show where uninit vals come from
valgrind --tool=memcheck --vgdb=yes --vgdb-error=0 ./myapp # Then attach with gdb for fine-grained inspection: # gdb ./myapp # (gdb) target remote | vgdb
# ASan is 2x faster than Valgrind: clang -fsanitize=address -fno-omit-frame-pointer -g -O1 -o myapp-asan myapp.c ./myapp-asan # Also: LeakSanitizer for leaks only clang -fsanitize=leak -g -o myapp-lsan myapp.c
Cachegrind
valgrind --tool=cachegrind ./myapp # Output: cachegrind.out.PID cg_annotate cachegrind.out.PID # Annotated source with miss counts # Use KCachegrind for GUI visualization
valgrind --tool=callgrind ./myapp callgrind_annotate callgrind.out.PID # Open in KCachegrind (GUI) for interactive caller/callee tree # qcachegrind on macOS
Massif
valgrind --tool=massif ./myapp # Output: massif.out.PID ms_print massif.out.PID | head -50 # Text chart of heap usage over time # Use massif-visualizer for GUI
Helgrind
valgrind --tool=helgrind ./myapp-threaded # Reports: conflicting accesses, lock ordering violations
Suppressions
# Create suppression file:
cat > suppressions.txt <<EOF
{
ignore_libc_memcpy
Memcheck:Overlap
fun:memcpy
}
EOF
valgrind --suppressions=suppressions.txt ./myapp