1、Valgrind安裝
valgrind是一款用於內存調試、內存泄漏檢測以及性能分析的軟件開發工具。
在安裝valgrind以前,要先安裝autoconf和automake。您能夠使用命令autoconf --version和automake --version檢查這兩個工具是否有安裝。html
(1)下載最新的安裝包數組
http://valgrind.org/downloads/current.htmlapp
或者是輸入命令:工具
wget http://valgrind.org/downloads/valgrind-3.10.1.tar.bz2性能
(2)解壓縮安裝包,輸入命令:開發工具
tar -jxvf valgrind-3.10.1.tar.bz2測試
(3)進入解壓縮後生成的目錄valgrind-3.10.1,輸入命令:.net
cd valgrind-3.10.1調試
(4)運行./autogen.sh設置環境,輸入命令:htm
./autogen.sh
若是你碰到以下錯誤:aclocal: command not found
則表示你須要安裝autoconf和automake兩個工具,請先查看「安裝autoconf「和」安裝automake「兩個步驟。
(5)運行configure文件,生成Makefile。
(6)編譯並安裝valgrind,輸入命令:
make;make install
(7)檢查安裝是否成功:
valgrind --version
2、測試代碼:
#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: 內存沒有釋放
}
編譯:g++ -g -o testdump main.cpp
Valgrind檢查:valgrind --tool=memcheck --leak-check=yes ./testdump
說明:
Invalid write of size 4:表示數組越界寫了4字節;
40 bytes in 1 blocks:表示因程序退出而發生內存泄露40字節;
修改Bug以後再進行valgrind檢查:沒有了內存泄漏和數組越界問題!
小結:
1、Valgrind 中包含的 Memcheck 工具能夠檢查如下的程序錯誤:
(1)使用未初始化的內存 (Use of uninitialised memory)
(2)使用已經釋放了的內存 (Reading/writing memory after it has been free'd)
(3)使用超過malloc分配的內存空間(Reading/writing off the end of malloc'd blocks)
(4)對堆棧的非法訪問 (Reading/writing inappropriate areas on the stack)
(5)申請的空間是否有釋放 (Memory leaks – where pointers to malloc'd blocks are lost forever)
(6)malloc/free/new/delete申請和釋放內存的匹配(Mismatched use of malloc/new/new [] vs free/delete/delete [])
(7)src和dst的重疊(Overlapping src and dst pointers in memcpy() and related functions)
(8)重複free
2、工程經驗
對於寫好的代碼,想要檢查是否存在內存問題,能夠結合Coverity靜態內存檢查和Valgrind內存檢測。注意:Coverity靜態檢測不能檢測動態內存問題。 --------------------- 做者:SoaringLee_fighting 來源:CSDN 原文:https://blog.csdn.net/soaringlee_fighting/article/details/77925402 版權聲明:本文爲博主原創文章,轉載請附上博文連接!