由于C和C++程序中常常需要程序員自主申請(qǐng)和釋放內(nèi)存酵使,在大型的钟些、復(fù)雜的應(yīng)用程序中就會(huì)常常出現(xiàn)內(nèi)存錯(cuò)誤吮螺。Valgrind是linux環(huán)境下的一款功能齊全的內(nèi)存調(diào)試和性能分析工具集洗鸵,它包括Memcheck
斩跌、Callgrind
尊残、Cachegrind
炒瘸、Helgrind
、Massif
等工具寝衫。
本文分為三個(gè)部分:valgrind工具的下載與安裝顷扩、實(shí)例解析、常用選項(xiàng)說明慰毅。通過這三部分的學(xué)習(xí)隘截,讀者可以基本掌握valgrind工具的內(nèi)存調(diào)試方法。
1. 下載與安裝
sudo apt install valgrind
2. 實(shí)例解析
#include<stdlib.h>
#include<iostream>
using namespace std;
void GetMemory(char*p,int num)
{
p=(char*)malloc(sizeof(char)*num);// 申請(qǐng)了內(nèi)存但是沒有釋放
}
int main(int argc,char**argv)
{
char*str=NULL;
GetMemory(str,100);
cout<<"Memory leak test!"<<endl;
return 0;
}
編譯上述代碼汹胃,得到可執(zhí)行文件test婶芭。使用Valgrind允許可執(zhí)行文件如下圖所示://11950 為進(jìn)程ID
==11950== 100 bytes in 1 blocks are definitely lost in loss record 1 of 2
==11950== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==11950== by 0x4008B1: GetMemory(char*, int) (in /home/zz/code/test)
==11950== by 0x4008E0: main (in /home/zz/code/test)
上面的結(jié)果告訴我們是在main中調(diào)用了GetMemory導(dǎo)致的內(nèi)存泄漏,GetMemory中是調(diào)用了malloc導(dǎo)致泄漏了100字節(jié)的內(nèi)存着饥。
3. Valgrind工具選項(xiàng)說明
valgrind 命令的基本格式為:valgrind [base option] --tool=<tool name> [tool option] your-program [program options]
本文僅列出了一些常用的選項(xiàng)犀农,更詳細(xì)的選項(xiàng)說明可參考valgrind home網(wǎng)站上的相關(guān)章節(jié)(http://www.valgrind.org/)。
a) Valgrind基本選項(xiàng)及其說明
--tool
:指定使用的具體工具宰掉,可以為Memcheck呵哨、Callgrind、Cachegrind轨奄、Helgrind孟害、Massif等工具;
b) Memcheck相關(guān)選項(xiàng)及其說明
--leak-check=<no|summary|yes|full> [default: summary]
:no表示不檢測(cè),summary只顯示統(tǒng)計(jì)信息挪拟,yes和full顯示詳細(xì)信息挨务,即上述四種泄露的詳細(xì)信息。