Unix下C程序內存泄漏檢測工具Valgrind安裝與使用

Unix下C程序內存泄漏檢測工具Valgrind安裝與使用

Valgrind是一款用於內存調試、內存泄漏檢測以及性能分析的軟件開發工具。html

Valgrind的最初做者是Julian Seward,他於2006年因爲在開發Valgrind上的工做得到了第二屆Google-O'Reilly開源代碼獎。web

Valgrind遵照GNU通用公共許可證條款,是一款自由軟件。數組

 

官網app

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開發工具

 

測試代碼測試

  1. #include
  2. int* func(void)
  3. {
  4.     int* x = malloc(10 * sizeof(int));
  5.     x[10] = 0; //問題1: 數組下標越界
  6. }
  7. int main(void)
  8. {
  9.     int* x=NULL;
  10.     x=func();
  11.     //free(x);
  12.     x=NULL;
  13.     return 0; //問題2: 內存沒有釋放
  14. }

編譯google

#gcc -g -o test test.c.net

 

內存檢查
#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

 

其餘參考工具:likwid http://code.google.com/p/likwid/downloads/list

 

 ref: http://blog.sina.com.cn/s/blog_af9acfc601017vhs.html
相關文章
相關標籤/搜索