Valgrind是一款用于內(nèi)存調(diào)試、內(nèi)存泄漏檢測(cè)以及性能分析的軟件開發(fā)工具。
Valgrind的最初作者是Julian Seward,他于2006年由于在開發(fā)Valgrind上的工作獲得了第二屆Google-O'Reilly開源代碼獎(jiǎng)。
Valgrind遵守GNU通用公共許可證條款,是一款自由軟件。
官網(wǎng)
http://www.valgrind.org
下載與安裝
#wget http://www.valgrind.org/downloads/valgrind-3.8.1.tar.bz2
#tar xvf valgrind-3.8.1.tar.bz2
#cd valgrind-3.8.1
#./configure --prefix=/usr/local/webserver/valgrind
#make
#make install
測(cè)試代碼
復(fù)制代碼 代碼如下:
#include <stdlib.h>
int* func(void)
{
int* x = malloc(10 * sizeof(int));
x[10] = 0; //問題1: 數(shù)組下標(biāo)越界
}
int main(void)
{
int* x=NULL;
x=func();
//free(x);
x=NULL;
return 0; //問題2: 內(nèi)存沒有釋放
}
編譯
#gcc -g -o test test.c
內(nèi)存檢查
#valgrind --tool=memcheck --leak-check=yes --show-reachable=yes ./test
報(bào)告:
說明
Invalid write of size 4:表示數(shù)組越界寫了4字節(jié)
40 bytes in 1 blocks:表示因程序退出而發(fā)生內(nèi)存泄露40字節(jié)
修復(fù)bug,重新檢查提示已經(jīng)沒有內(nèi)存泄露
文檔:
Valgrind 中包含的 Memcheck 工具可以檢查以下的程序錯(cuò)誤:
使用未初始化的內(nèi)存 (Use of uninitialised memory)
使用已經(jīng)釋放了的內(nèi)存 (Reading/writing memory after it has been free'd)
使用超過malloc分配的內(nèi)存空間(Reading/writing off the end of malloc'd blocks)
對(duì)堆棧的非法訪問 (Reading/writing inappropriate areas on the stack)
申請(qǐng)的空間是否有釋放 (Memory leaks – where pointers to malloc'd blocks are lost forever)
malloc/free/new/delete申請(qǐng)和釋放內(nèi)存的匹配(Mismatched use of malloc/new/new [] vs free/delete/delete [])
src和dst的重疊(Overlapping src and dst pointers in memcpy() and related functions)
重復(fù)free