$devvkit learn --librarie valgrind-guide
Valgrind Guide
[memory][debugging][profiling][c-cpp]
Performance & Profiling
Install
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
Memory leak check— Find unreleased memory.
valgrind --leak-check=full --show-leak-kinds=all ./myapp valgrind --leak-check=full --track-origins=yes ./myapp # Show where uninit vals come from
Invalid access— Buffer overflow detection.
valgrind --tool=memcheck --vgdb=yes --vgdb-error=0 ./myapp # Then attach with gdb for fine-grained inspection: # gdb ./myapp # (gdb) target remote | vgdb
Trick: shallow with ASan— Faster alternative.
# 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
Cache profiling— L1/L2/LLC misses.
valgrind --tool=cachegrind ./myapp # Output: cachegrind.out.PID cg_annotate cachegrind.out.PID # Annotated source with miss counts # Use KCachegrind for GUI visualization
Call-graph profiling— Function call counts.
valgrind --tool=callgrind ./myapp callgrind_annotate callgrind.out.PID # Open in KCachegrind (GUI) for interactive caller/callee tree # qcachegrind on macOS
Massif
Heap profiler— Memory usage over time.
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
Thread race detection— Find data races.
valgrind --tool=helgrind ./myapp-threaded # Reports: conflicting accesses, lock ordering violations
Suppressions
Suppression file— Ignore known false positives.
# Create suppression file:
cat > suppressions.txt <<EOF
{
ignore_libc_memcpy
Memcheck:Overlap
fun:memcpy
}
EOF
valgrind --suppressions=suppressions.txt ./myapp