Unix下C程式記憶體洩漏檢測工具Valgrind安裝與使用
Valgrind是一款用於記憶體除錯、記憶體洩漏檢測以及效能分析的軟體開發工具。
Valgrind的最初作者是Julian Seward,他於2006年由於在開發Valgrind上的工作獲得了第二屆Google-O'Reilly開原始碼獎。
Valgrind遵守GNU通用公共許可證條款,是一款自由軟體。
官網
下載與安裝
#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: 陣列下標越界} int main(void){ int* x=NULL; x=func(); //free(x); x=NULL; return 0; //問題2: 記憶體沒有釋放 }
編譯
#gcc -g -o test test.c
記憶體檢查#valgrind --tool=memcheck --leak-check=yes --show-reachable=yes ./test
報告:
說明
Invalid write of size 4:表示陣列越界寫了4位元組
40 bytes in 1 blocks:表示因程式退出而發生記憶體洩露40位元組
修復bug,重新檢查提示已經沒有記憶體洩露
文件:
Valgrind 中包含的 Memcheck 工具可以檢查以下的程式錯誤: 使用未初始化的記憶體 (Use of uninitialised memory) 使用已經釋放了的記憶體 (Reading/writing memory after it has been free’d) 使用超過malloc分配的記憶體空間(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申請和釋放記憶體的匹配(Mismatched use of malloc/new/new [] vs free/delete/delete []) src和dst的重疊(Overlapping src and dst pointers in memcpy() and related functions) 重複free