Unix下C程序内存泄漏检测工具Valgrind安装与使用
Valgrind是一款用于內(nèi)存調(diào)試、內(nèi)存泄漏檢測以及性能分析的軟件開發(fā)工具。
Valgrind的最初作者是Julian Seward,他于2006年由于在開發(fā)Valgrind上的工作獲得了第二屆Google-O'Reilly開源代碼獎。
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
?
測試代碼
#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
?
報告:
?
說明
?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 工具可以檢查以下的程序錯誤:
使用未初始化的內(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)
對堆棧的非法訪問 (Reading/writing inappropriate areas on the stack)
申請的空間是否有釋放 (Memory leaks – where pointers to malloc’d blocks are lost forever)
malloc/free/new/delete申請和釋放內(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
?
其他參考工具:likwid? http://code.google.com/p/likwid/downloads/list
總結(jié)
以上是生活随笔為你收集整理的Unix下C程序内存泄漏检测工具Valgrind安装与使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux进程间通信--进程,信号,管道
- 下一篇: Java开发环境的搭建以及使用eclip