Valgrind
Purpose
Guide agents through Valgrind tools: Memcheck for memory errors, Cachegrind for cache simulation, Callgrind for call graphs, and Massif for heap profiling.
Triggers
- "My program has a memory leak / use-after-free"
- "I can't use ASan — can I use Valgrind instead?"
- "How do I profile cache behaviour without perf?"
- "How do I visualize call graphs with Callgrind?"
- "How do I profile heap allocation patterns?"
- "Valgrind reports errors in third-party code I can't fix"
Workflow
1. Memcheck — memory error detection
Compile with -g -O1 for best results. -O0 is also fine; avoid -O2+ which can produce false positives.
Key flags:
2. Understanding Memcheck output
- Invalid read/write: out-of-bounds access; check array bounds
- Use of uninitialised value: read before write; use
--track-origins=yes - Invalid free / double free: mismatched malloc/free; check ownership
- Definitely lost: reachable via no pointers; clear leak
- Indirectly lost: lost through a chain; usually means one root leak
- Possibly lost: might be pointing into the middle of a block; often FP with custom allocators
3. Leak kinds
For library code: --show-leak-kinds=definite,indirect reduces noise from still-reachable.
4. Suppressions
5. Cachegrind — cache simulation
Key metrics:
I1mr/ILmr: L1/LL instruction cache miss rateD1mr/DLmr: L1/LL data read miss rateD1mw/DLmw: L1/LL data write miss rate
6. Callgrind — call graph profiling
Callgrind is slower than perf but works without root and provides exact call counts.
7. Massif — heap profiling
Massif shows heap usage over time; useful for finding peak allocation sites and tracking gradual leaks.
8. Performance considerations
Valgrind Memcheck runs ~10-50x slower than native. Mitigations:
- Use a shorter representative workload
- Use
--error-exitcode=1to fail fast in CI - Use ASan (
-fsanitize=address) for faster memory checking during development - Reserve Valgrind for cases where ASan can't be used (old toolchains, production-like environments)
For a comparison of Valgrind vs ASan, see references/valgrind-vs-asan.md [blocked].
Related skills
- Use
skills/runtimes/sanitizersfor faster ASan/UBSan alternatives - Use
skills/profilers/linux-perffor CPU-level profiling (faster than Cachegrind) - Use
skills/profilers/flamegraphsto visualise Callgrind output


