天天看點

c程式記憶體洩露檢查工具

Valgrind是一款用于記憶體調試、記憶體洩漏檢測以及性能分析的軟體開發工具。

Valgrind的最初作者是Julian Seward,他于2006年由于在開發Valgrind上的工作獲得了第二屆Google-O'Reilly開源代碼獎。

Valgrind遵守GNU通用公共許可證條款,是一款自由軟體。

官網

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;

}

int main(void)

{

int* x=NULL;

x=func();

//free(x);  

x=NULL;

return 0;

}

編譯

#gcc -g -o test test.c

記憶體檢查

/usr/local/webserver/valgrind/bin/valgrind --tool=memcheck --leak-check=yes --show-reachable=yes /data_disk/webdata/c/test

檢查結果

==27394== Memcheck, a memory error detector

==27394== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.

==27394== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info

==27394== Command: /data_disk/webdata/c/test

==27394== 

==27394== Invalid write of size 4

==27394==    at 0x4004E2: func (test.c:5)

==27394==    by 0x4004FE: main (test.c:10)

==27394==  Address 0x51c2068 is 0 bytes after a block of size 40 alloc'd

==27394==    at 0x4C278FE: malloc (vg_replace_malloc.c:270)

==27394==    by 0x4004D5: func (test.c:4)

==27394==    by 0x4004FE: main (test.c:10)

==27394== 

==27394== 

==27394== HEAP SUMMARY:

==27394==     in use at exit: 40 bytes in 1 blocks

==27394==   total heap usage: 1 allocs, 0 frees, 40 bytes allocated

==27394== 

==27394== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1

==27394==    at 0x4C278FE: malloc (vg_replace_malloc.c:270)

==27394==    by 0x4004D5: func (test.c:4)

==27394==    by 0x4004FE: main (test.c:10)

==27394== 

==27394== LEAK SUMMARY:

==27394==    definitely lost: 40 bytes in 1 blocks

==27394==    indirectly lost: 0 bytes in 0 blocks

==27394==      possibly lost: 0 bytes in 0 blocks

==27394==    still reachable: 0 bytes in 0 blocks

==27394==         suppressed: 0 bytes in 0 blocks

==27394== 

==27394== For counts of detected and suppressed errors, rerun with: -v

==27394== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 6 from 6)

說明

 Invalid write of size 4:表示數組越界寫了4位元組

40 bytes in 1 blocks:表示因程式退出而發生記憶體洩露40位元組

文檔:

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

繼續閱讀