Valgrind使用記錄

C++ Dec 7, 2019

Cover:https://www.pexels.com/photo/man-in-white-shirt-using-macbook-pro-52608/

最近要用Valgrind來偵測Memory的泄漏,除了memory leak之外,更可檢測到其他memory問題,相當實用。

install(not tested yet):

apt install valgrind

Compile C++ program:

g++ -std=c++11 main.cpp foo.cpp -g

一定要加-gflag !!!否則看不到哪行問題@.@

執行Valgrind:

valgrind --leak-check=full ./a.out

若有以下output,則有memory問題:

==26518== ERROR SUMMARY: 3 errors from 3 contexts (suppressed: 0 from 0)
==26518== ERROR SUMMARY: 3 errors from 3 contexts (suppressed: 0 from 0)

若有以下output,則有memory leak問題:

==26518== LEAK SUMMARY:
==26518==    definitely lost: 128 bytes in 3 blocks
==26518==    indirectly lost: 0 bytes in 0 blocks
==26518==      possibly lost: 0 bytes in 0 blocks
==26518==    still reachable: 0 bytes in 0 blocks
==26518==         suppressed: 0 bytes in 0 blocks

若有以下output,則無memory問題:

==12712== HEAP SUMMARY:
==12712==     in use at exit: 0 bytes in 0 blocks
==12712==   total heap usage: 18 allocs, 18 frees, 720 bytes allocated
==12712==
==12712== All heap blocks were freed -- no leaks are possible
==12712==
==12712== For counts of detected and suppressed errors, rerun with: -v
==12712== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

有memory問題可以檢查之前的output:

60 bytes in 1 blocks are definitely lost in loss record 1 of 1
   at 0x4C2BB78: realloc (vg_replace_malloc.c:785)
   by 0x4005E4: resizeArray (main.c:12)
   by 0x40062E: main (main.c:19)

代表由main call的 main.c的第12行有問題,可檢查關於dynamic variable, pointers等等的code。

標籤