valgrind 內存泄露工具使用

valgrind 內存泄露工具使用

安裝軟件

sudo apt-get install valgrind

測試算例

#include <stdlib.h>
 
void f(void)
{
	int* x = malloc(10 * sizeof(int));
	x[10] = 0; // problem 1: heap block overrun
			   // problem 2: memory leak -- x not freed
}
 
int main(void)
{
	f();
	return 0;
}

如果以下面的語句運行

gcc -g -o testValgrind testValgrind.c
valgrind --tool=memcheck --leak-check=yes ./testValgrind 

其中valgrind表示用的是memcheck工具包,使用了該工具包的檢測內存泄露功能,**注意在編譯程序的時候加上-g選項,打印錯誤信息的時候會給出行號。**可得到下面的結果

==18284== Memcheck, a memory error detector
==18284== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==18284== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==18284== Command: ./testValgrind
==18284== 
==18284== Invalid write of size 4
==18284==    at 0x108668: f (testValgrind.c:6)
==18284==    by 0x108679: main (testValgrind.c:12)
==18284==  Address 0x522d068 is 0 bytes after a block of size 40 alloc'd
==18284==    at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==18284==    by 0x10865B: f (testValgrind.c:5)
==18284==    by 0x108679: main (testValgrind.c:12)
==18284== 
==18284== 
==18284== HEAP SUMMARY:
==18284==     in use at exit: 40 bytes in 1 blocks
==18284==   total heap usage: 1 allocs, 0 frees, 40 bytes allocated
==18284== 
==18284== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1
==18284==    at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==18284==    by 0x10865B: f (testValgrind.c:5)
==18284==    by 0x108679: main (testValgrind.c:12)
==18284== 
==18284== LEAK SUMMARY:
==18284==    definitely lost: 40 bytes in 1 blocks
==18284==    indirectly lost: 0 bytes in 0 blocks
==18284==      possibly lost: 0 bytes in 0 blocks
==18284==    still reachable: 0 bytes in 0 blocks
==18284==         suppressed: 0 bytes in 0 blocks
==18284== 
==18284== For counts of detected and suppressed errors, rerun with: -v
==18284== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)

查看結果可以看出,在主函數的12行,子函數的第6行存在問題,地址對應0字節,子函數的第5行的問題在於空間沒有釋放.

主要的功能

Memcheck:主要檢查的程序錯誤包括

(1)、使用未初始化的內存;

(2)、讀寫已經釋放了的內存;

(3)、使用超過malloc分配的內存空間;

(4)、對堆棧的非法訪問;

(5)、申請的空間是否有釋放;

(6)、malloc/free/new/delete申請和釋放內存的匹配;

(7)、src和dst指針的重疊;

(8)、將無意義的參數傳遞給系統調用。

參考文獻:

  1. 它人博客:ubuntu 上使用valgrind
  2. 官方說明書:The Valgrind Quick Start Guide
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章