《轉》防止記憶體泄露 Linux下用Valgrind做檢查

來源:互聯網
上載者:User

對於線上程式,真心還沒感覺沒啥用,或者是我不會用

=================================================================================

用C/C++開發其中最令人頭疼的一個問題就是記憶體管理,有時候為了尋找一個記憶體流失或者一個記憶體訪問越界,需要要花上好幾天時間,如果有一款工具能夠協助我們做這件事情就好了,valgrind正好就是這樣的一款工具。

 

Valgrind是一款基於類比linux下的程式調試器和剖析器的軟體套件,可以運行於x86, amd64和ppc32架構上。valgrind包含一個核心,它提供一個虛擬CPU運行程式,還有一系列的工具,它們完成調試,剖析和一些類似的任務。valgrind是高度模組化的,所以開發人員或者使用者可以給它添加新的工具而不會損壞己有的結構。

 

valgrind的官方網址是:http://valgrind.org

你可以在它的網站上下載到最新的valgrind,它是開放源碼和免費的。

 

一、介紹

 

valgrind包含幾個標準的工具,它們是:

 

1、memcheck

 

memcheck探測程式中記憶體管理存在的問題。它檢查所有對記憶體的讀/寫操作,並截取所有的malloc/new/free/delete調用。因此memcheck工具能夠探測到以下問題:

 

1)使用未初始化的記憶體

2)讀/寫已經被釋放的記憶體

3)讀/寫記憶體越界

4)讀/寫不恰當的記憶體棧空間

5)記憶體流失

6)使用malloc/new/new[]和free/delete/delete[]不匹配。

 

2、cachegrind

 

cachegrind是一個cache剖析器。它類比執行CPU中的L1, D1和L2 cache,因此它能很精確的指出代碼中的cache未命中。如果你需要,它可以列印出cache未命中的次數,記憶體引用和發生cache未命中的每一行代碼,每一個函數,每一個模組和整個程式的摘要。如果你要求更細緻的資訊,它可以列印出每一行機器碼的未叫用次數。在x86和amd64上,cachegrind通過CPUID自動探測機器的cache配置,所以在多數情況下它不再需要更多的配置資訊了。

 

3、helgrind

 

helgrind尋找多線程程式中的競爭資料。helgrind尋找記憶體位址,那些被多於一條線程訪問的記憶體位址,但是沒有使用一致的鎖就會被查出。這表示這些地址在多線程間訪問的時候沒有進行同步,很可能會引起很難尋找的時序問題。

 

二、valgrind對你的程式都做了些什麼

 

valgrind被設計成非侵入式的,它直接工作於可執行檔上,因此在檢查前不需要重新編譯、串連和修改你的程式。要檢查一個程式很簡單,只需要執行下面的命令就可以了

 

valgrind --tool=tool_name program_name

 

比如我們要對ls -l命令做記憶體檢查,只需要執行下面的命令就可以了

 

valgrind --tool=memcheck ls -l

 

不管是使用哪個工具,valgrind在開始之前總會先取得對你的程式的控制權,從可執行關聯庫裡讀取調試資訊。然後在valgrind核心提供的虛擬CPU上運行程式,valgrind會根據選擇的工具來處理代碼,該工具會向代碼中加入檢測代碼,並把這些代碼作為最終代碼返回給valgrind核心,最後valgrind核心運行這些代碼。

 

如果要檢查記憶體流失,只需要增加--leak-check=yes就可以了,命令如下

 

valgrind --tool=memcheck --leak-check=yes ls -l

 

不同工具間加入的代碼變化非常的大。在每個範圍的末尾,memcheck加入代碼檢查每一片記憶體的訪問和進行值計算,代碼大小至少增加12倍,運行速度要比平時慢25到50倍。

 

valgrind類比程式中的每一條指令執行,因此,檢查工具和剖析工具不僅僅是對你的應用程式,還有對共用庫,GNU C庫,X的用戶端庫都起作用。

 

三、現在開始

 

首先,在編譯器的時候開啟偵錯模式(gcc編譯器的-g選項)。如果沒有調試資訊,即使最好的valgrind工具也將中能夠猜測特定的代碼是屬於哪一個函數。開啟調試選項進行編譯後再用valgrind檢查,valgrind將會給你的個詳細的報告,比如哪一行代碼出現了記憶體流失。

 

當檢查的是C++程式的時候,還應該考慮另一個選項 -fno-inline。它使得函數調用鏈很清晰,這樣可以減少你在瀏覽大型C++程式時的混亂。比如在使用這個選項的時候,用memcheck檢查openoffice就很容易。當然,你可能不會做這項工作,但是使用這一選項使得valgrind產生更精確的錯誤報表和減少混亂。

 

一些編譯最佳化選項(比如-O2或者更高的最佳化選項),可能會使得memcheck提交錯誤的未初始化報告,因此,為了使得valgrind的報告更精確,在編譯的時候最好不要使用最佳化選項。

 

如果程式是通過指令碼啟動的,可以修改指令碼裡啟動程式的代碼,或者使用--trace-children=yes選項來運行指令碼。

 

下面是用memcheck檢查ls -l命令的輸出報告,在終端下執行下面的命令

 

valgrind --tool=memcheck ls -l

 

程式會列印出ls -l命令的結果,最後是valgrind的檢查報告如下:

 

==4187==

==4187== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 19 from 2)

==4187== malloc/free: in use at exit: 15,154 bytes in 105 blocks.

==4187== malloc/free: 310 allocs, 205 frees, 60,093 bytes allocated.

==4187== For counts of detected errors, rerun with: -v

==4187== searching for pointers to 105 not-freed blocks.

==4187== checked 145,292 bytes.

==4187==

==4187== LEAK SUMMARY:

==4187== definitely lost: 0 bytes in 0 blocks.

==4187== possibly lost: 0 bytes in 0 blocks.

==4187== still reachable: 15,154 bytes in 105 blocks.

==4187== suppressed: 0 bytes in 0 blocks.

==4187== Reachable blocks (those to which a pointer was found) are not shown.

==4187== To see them, rerun with: --show-reachable=yes

 

這裡的“4187”指的是執行ls -l的進程ID,這有利於區別不同進程的報告。memcheck會給出報告,分配置和釋放了多少記憶體,有多少記憶體流失了,還有多少記憶體的訪問是可達的,檢查了多少位元組的記憶體。

 

下面舉兩個用valgrind做記憶體檢查的例子

 

例子一 (test.c):

 

 

#include <string.h>int main(int argc, char *argv[]){    char *ptr;    ptr = (char*) malloc(10);    strcpy(ptr, "01234567890");    return 0;}

 

編譯器

 

gcc -g -o test test.c

 

用valgrind執行命令

 

valgrind --tool=memcheck --leak-check=yes ./test

 

報告如下

 

==4270== Memcheck, a memory error detector.

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

==4270== Using LibVEX rev 1606, a library for dynamic binary translation.

==4270== Copyright (C) 2004-2006, and GNU GPL'd, by OpenWorks LLP.

==4270== Using valgrind-3.2.0, a dynamic binary instrumentation framework.

==4270== Copyright (C) 2000-2006, and GNU GPL'd, by Julian Seward et al.

==4270== For more details, rerun with: -v

==4270==

==4270== Invalid write of size 1

==4270== at 0x4006190: strcpy (mc_replace_strmem.c:271)

==4270== by 0x80483DB: main (test.c:8)

==4270== Address 0x4023032 is 0 bytes after a block of size 10 alloc'd

==4270== at 0x40044F6: malloc (vg_replace_malloc.c:149)

==4270== by 0x80483C5: main (test.c:7)

==4270==

==4270== Invalid write of size 1

==4270== at 0x400619C: strcpy (mc_replace_strmem.c:271)

==4270== by 0x80483DB: main (test.c:8)

==4270== Address 0x4023033 is 1 bytes after a block of size 10 alloc'd

==4270== at 0x40044F6: malloc (vg_replace_malloc.c:149)

==4270== by 0x80483C5: main (test.c:7)

==4270==

==4270== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 12 from 1)

==4270== malloc/free: in use at exit: 10 bytes in 1 blocks.

==4270== malloc/free: 1 allocs, 0 frees, 10 bytes allocated.

==4270== For counts of detected errors, rerun with: -v

==4270== searching for pointers to 1 not-freed blocks.

==4270== checked 51,496 bytes.

==4270==

==4270==

==4270== 10 bytes in 1 blocks are definitely lost in loss record 1 of 1

==4270== at 0x40044F6: malloc (vg_replace_malloc.c:149)

==4270== by 0x80483C5: main (test.c:7)

==4270==

==4270== LEAK SUMMARY:

==4270== definitely lost: 10 bytes in 1 blocks.

==4270== possibly lost: 0 bytes in 0 blocks.

==4270== still reachable: 0 bytes in 0 blocks.

==4270== suppressed: 0 bytes in 0 blocks.

==4270== Reachable blocks (those to which a pointer was found) are not shown.

==4270== To see them, rerun with: --show-reachable=yes

 

從這份報告可以看出,進程號是4270,test.c的第8行寫記憶體越界了,引起寫記憶體越界的是strcpy函數,

第7行泄漏了10個位元組的記憶體,引起記憶體流失的是malloc函數。

 

例子二(test2.c)

 

 

#include <stdio.h>int foo(int x){    if (x < 0) {        printf("%d ", x);    }    return 0;}int main(int argc, char *argv[]){    int x;       foo(x);    return 0;}

 

編譯器

 

gcc -g -o test2 test2.c

 

用valgrind做記憶體檢查

 

valgrind --tool=memcheck ./test2

 

輸出報告如下

 

==4285== Memcheck, a memory error detector.

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

==4285== Using LibVEX rev 1606, a library for dynamic binary translation.

==4285== Copyright (C) 2004-2006, and GNU GPL'd, by OpenWorks LLP.

==4285== Using valgrind-3.2.0, a dynamic binary instrumentation framework.

==4285== Copyright (C) 2000-2006, and GNU GPL'd, by Julian Seward et al.

==4285== For more details, rerun with: -v

==4285==

==4285== Conditional jump or move depends on uninitialised value(s)

==4285== at 0x8048372: foo (test2.c:5)

==4285== by 0x80483B4: main (test2.c:16)

==4285==p p

==4285== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 12 from 1)

==4285== malloc/free: in use at exit: 0 bytes in 0 blocks.

==4285== malloc/free: 0 allocs, 0 frees, 0 bytes allocated.

==4285== For counts of detected errors, rerun with: -v

==4285== All heap blocks were freed -- no leaks are possible.

 

從這份報告可以看出進程PID是4285,test2.c檔案的第16行調用了foo函數,在test2.c檔案的第5行foo函數使用了一個未初始化的變數。

 

valgrind還有很多使用選項,具體可以查看valgrind的man手冊頁和valgrind官方網站的線上文檔。

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.