Unix下C程序內(nèi)存泄漏檢測工具Valgrind的安裝與使用詳解
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ù)組下標越界
}
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é)
修復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)
重復free
- 深入探討:unix多進程編程之wait()與waitpid()函數(shù)
- FROM_UNIXTIME 格式化MYSQL時間戳函數(shù)
- PHP中UNIX時間戳和日期間的轉(zhuǎn)換與計算實例
- python正常時間和unix時間戳相互轉(zhuǎn)換的方法
- 深入Unix時間戳與C# DateTime時間類型互換的詳解
- UNIX 系統(tǒng)常用管理命令
- Linux/Unix環(huán)境下的Make和Makefile詳解
- Linux/Unix環(huán)境下的make命令詳解
- UNIX IP Stack 調(diào)整指南
- UNIX下的PHP環(huán)境配置,+apache
- unix 編程進程控制詳細介紹
相關(guān)文章
c++11?實現(xiàn)枚舉值到枚舉名的轉(zhuǎn)換問題
這篇文章主要介紹了c++11?實現(xiàn)枚舉值到枚舉名的轉(zhuǎn)換,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-03-03