Valgrind

mohitmishra786/low-level-dev-skills/skills/profilers/valgrind

作者 mohitmishra786bdc58472fa9f無授權條款253 個星標收錄於 2026年10月9日更新於 2026年10月9日儲存庫3 個月前更新

Valgrind profiler skill for memory error detection and cache profiling. Use when running Memcheck to find heap corruption, use-after-free, memory leaks, or uninitialised reads; or Cachegrind/Callgrind for cache simulation and function-level profiling. Activates on queries about valgrind, memcheck, heap leaks, use-after-free without sanitizers, cachegrind, callgrind, KCachegrind, or massif memory profiling.

AI 產生的概覽

引導代理使用 Valgrind 工具進行記憶體錯誤偵測、快取模擬、呼叫圖分析與堆積分析。

功能
此技能提供使用 Valgrind 的 Memcheck、Cachegrind、Callgrind 與 Massif 工具的說明。內容涵蓋編譯選項、命令列參數、如何解讀 Memcheck 報告與洩漏類型、抑制檔、快取指標、呼叫圖分析以及堆積分析輸出。它也說明效能開銷以及何時改用 AddressSanitizer,並附有一份比較 Valgrind 與 ASan 的參考文件。
適用情境
適用於程式出現記憶體洩漏、釋放後使用、堆積損毀或未初始化讀取,或無法使用 sanitizer 的情況。也適合快取行為分析、呼叫圖產生與堆積配置分析。
執行需求
需要安裝 Valgrind 及其配套工具(cg_annotate、cg_diff、callgrind_annotate、ms_print),可選安裝 KCachegrind 或 massif-visualizer 等圖形介面工具。此技能不含指令碼,僅為說明文件,並附有一份參考文件。

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.

bash
valgrind --tool=memcheck \         --leak-check=full \         --show-leak-kinds=all \         --track-origins=yes \         --error-exitcode=1 \         ./prog [args]

Key flags:

FlagDefaultEffect
--leak-check=fullsummaryFull leak details
--show-leak-kinds=alldefiniteShow all leak kinds
--track-origins=yesnoShow where uninit values came from (slow)
--error-exitcode=N0Exit N if errors found (CI integration)
--log-file=filestderrSave report to file
--suppressions=filenoneSuppress known FPs
--gen-suppressions=yesnoPrint suppression directives for errors
--max-stackframe=N2000000Increase for deep stacks
--malloc-fill=0xABoffFill allocated memory (detect uninit use)
--free-fill=0xCDoffFill freed memory (detect use-after-free)

2. Understanding Memcheck output

text
==12345== Invalid read of size 4==12345==    at 0x4007A2: foo (main.c:15)==12345==    by 0x400846: main (main.c:30)==12345==  Address 0x5204040 is 0 bytes after a block of size 40 alloc'd==12345==    at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck.so)==12345==    by 0x40074B: main (main.c:25)
  • 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

KindMeaning
Definitely lostNo pointer to block
Indirectly lostLost via another lost block
Possibly lostPointer into middle of block
Still reachablePointer exists at exit; not a leak but never freed

For library code: --show-leak-kinds=definite,indirect reduces noise from still-reachable.

4. Suppressions

bash
# Generate suppression for current errorvalgrind --gen-suppressions=yes ./prog 2>&1 | grep -A20 '{'
# Example suppression file (valgrind.supp){   openssl_uninit   Memcheck:Cond   fun:SHA256_Init   ...}
# Use suppression filevalgrind --suppressions=valgrind.supp ./prog

5. Cachegrind — cache simulation

bash
valgrind --tool=cachegrind ./prog
# Output: cachegrind.out.PID# Annotate sourcecg_annotate cachegrind.out.12345 --auto=yes
# Diff two runscg_diff cachegrind.out.before cachegrind.out.after

Key metrics:

  • I1mr / ILmr: L1/LL instruction cache miss rate
  • D1mr / DLmr: L1/LL data read miss rate
  • D1mw / DLmw: L1/LL data write miss rate

6. Callgrind — call graph profiling

bash
valgrind --tool=callgrind --callgrind-out-file=callgrind.out ./prog
# Analysecallgrind_annotate callgrind.out
# Visualise in KCachegrind (GUI)kcachegrind callgrind.out

Callgrind is slower than perf but works without root and provides exact call counts.

7. Massif — heap profiling

bash
valgrind --tool=massif ./prog
# Visualisems_print massif.out.PID | less
# GUImassif-visualizer massif.out.PID

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=1 to 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/sanitizers for faster ASan/UBSan alternatives
  • Use skills/profilers/linux-perf for CPU-level profiling (faster than Cachegrind)
  • Use skills/profilers/flamegraphs to visualise Callgrind output

來源與署名

來源:mohitmishra786/low-level-dev-skills位於skills/profilers/valgrind提交bdc5847

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架