Valgrind是x86架構Linux上的多重用途代碼剖析和內存調試工具。但它的主要功能還是對內存的調試,默認工具也是啓動memcheck。用戶可以在它的環境中運行程序來監視內存的使用情況,比如C語言中的malloc和free或者C++中的new和delete。
gdb主要用於調試,valgrind 則注重於檢測內存,典型用法如下:
valgrind --tool=memcheck --leak-check=yes ./myprogram
Valgrind主要檢測如下內存問題:
(1)使用未初始化的內存。
(2)使用已經釋放了的內存。
(3)使用超過malloc分配的內存空間。
(4)對堆棧的非法訪問。
(5)內存泄漏。
(6)malloc/free/new/delete非匹配的使用內存申請和釋放函數。
(7)使用memcpy等函數時源地址和目的地址的重疊錯誤。
其使用方法如下:
// valgrind 參數 程序及選項 |
1.Valgrind常用選項
表3-1~表3-4列出了Valgrind工具的常用選項。如表3-1所示爲Valgrind工具所有經常使用的公共選項說明。
表3-1 Valgrind公共選項
參 數 |
說 明 |
默 認 設 置 |
--tool=<name> |
使用名爲<name>Valgrind工具 |
[memcheck] |
--version |
顯示版本信息 |
|
-q --quiet |
只打印錯誤信息 |
|
-v --verbose |
顯示詳細信息 |
|
--trace-children=no|yes |
跟蹤子進程 |
[no] |
--track-fds=no|yes |
跟蹤文件描述符 |
[no] |
--time-stamp=no|yes |
添加時間戳到日誌文件 |
[no] |
--log-fd=<number> |
日誌信息寫入到文件描述符 |
[2=stderr] |
--log-file=<file> |
日誌信息寫入到文件 |
|
--log-file-exactly=<file> |
日誌信息寫入到外部文件 |
<file> |
表3-2 Valgrind選項
參 數 |
說 明 |
默 認 設置 |
--run-libc-freeres=no|yes |
在退出時清除glibc內存 |
[yes] |
--sim-hints=hint1,hint2,... |
lax-ioctls, enable-outer |
[none] |
--show-emwarns=no|yes |
顯示仿真限制的警告 |
[no] |
--smc-check=none|stack|all |
自修改代碼檢查、不檢查、僅檢查棧中的代碼 |
[stack] |
--kernel-variant=variant1,... |
處理非標準內核變量 |
[none] |
表3-3 報告錯誤工具選項
參 數 |
說 明 |
默 認 設 置 |
--xml=yes |
所有輸出爲XML |
|
--xml-user-comment=STR |
逐字拷貝STR到XML |
|
--demangle=no|yes |
是否自動解除C++名稱修飾 |
[yes] |
--num-callers=<number> |
顯示棧跟蹤器中的number號調用者 |
[12] |
--error-limit=no|yes |
如果錯誤太多停止顯示新錯誤 |
[yes] |
--error-exitcode=<number> |
如果發現錯誤返回exit代碼 |
[0=disable] |
--show-below-main=no|yes |
在main後繼續跟蹤棧 |
[no] |
--suppressions=<filename> |
抑制文件中的錯誤描述 |
|
--gen-suppressions=no|yes|all |
打印錯誤的抑制信息 |
[no] |
--db-attach=no|yes |
發現錯誤時調試 |
[no] |
--db-command=<command> |
開始調試命令 |
[gdb -nw %f %p] |
--input-fd=<number> |
用於輸入的文件描述符 |
[0=stdin] |
--max-stackframe=<number> |
假設因sp變化大於number字節而引起堆轉變 |
[2000000] |
表3-4 Memcheck工具
參 數 |
說 明 |
默 認 設置 |
--leak-check=no|summary|full |
在exit處查找內存泄漏 |
[summary] |
--leak-resolution=low|med|high |
在內存泄漏檢查出多少字節 |
[low] |
--show-reachable=no|yes |
顯示泄露檢查中的塊 |
[no] |
--undef-value-errors=no|yes |
檢查未定義變量錯誤 |
[yes] |
--partial-loads-ok=no|yes |
請參閱手冊 |
[no] |
--freelist-vol=<number> |
釋放塊隊列的序號 |
[5000000] |
--workaround-gcc296-bugs=no|yes |
自解釋 |
[no] |
--alignment=<number> |
設置分配的最小對齊大小 |
[8] |