0%

Introduction Valgrind

Valgrind是一套用來動態分析程式的框架,他提供一組程式,用來測試,最佳化,及幫助改善程式的方案,你也可以自行開發工具加入Valgrind框架裡面,幫助測試你的程式。

目前的Valgrind套件主要包含了

  • memcheck
  • Cachegrind
  • Callgrind
  • Helgrind
  • DRD
  • Massif
  • DHAT
  • SGcheck
  • BBV

我們以最常遇到的Memory Leak來介紹, 編譯的時候記得加-g帶除錯參數

以下是Valgrind分析的結果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
$:~/test$ valgrind --tool=memcheck  --leak-check=full ./main
==4886== Memcheck, a memory error detector
==4886== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==4886== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==4886== Command: ./main
==4886==
==4886==
==4886== HEAP SUMMARY:
==4886== in use at exit: 10 bytes in 1 blocks
==4886== total heap usage: 1 allocs, 0 frees, 10 bytes allocated
==4886==
==4886== 10 bytes in 1 blocks are definitely lost in loss record 1 of 1
==4886== at 0x4C2B6CD: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4886== by 0x400505: main (main.cpp:3)
==4886==
==4886== LEAK SUMMARY:
==4886== definitely lost: 10 bytes in 1 blocks
==4886== indirectly lost: 0 bytes in 0 blocks
==4886== possibly lost: 0 bytes in 0 blocks
==4886== still reachable: 0 bytes in 0 blocks
==4886== suppressed: 0 bytes in 0 blocks
==4886==
==4886== For counts of detected and suppressed errors, rerun with: -v
==4886== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 2 from 2)

由於我們有待除錯參數,所以我們可以發現Memory Leak發生在main.cpp的第三行。

Valgrind不只可以偵測一般的執行檔,連Static Library跟SharedObject都可以偵測,只要記得編譯時帶除錯參數。