2012-09-25 98 views
1

Valgrind的告訴我:C++ Valgrind的內存泄露

==19305== 16 bytes in 1 blocks are definitely lost in loss record 19 of 179 
==19305== at 0x402842F: operator new(unsigned int) 
==19305== by 0x805273E: Loader::createLevel(int, int, std::string, Player*, int, int, int) 
==19305== by 0x80551B0: Loader::loadLevel() 
==19305== by 0x80676C2: main (main.cpp:38) 

我的功能Loader:.createLevel得到了幾個new語句。我怎麼知道他們中的哪一個造成泄漏(即線路)?

謝謝!

P.S:我很樂意發佈代碼,但它是太長:/

+0

簡單而長期的解決方案是將使用'new'創建的數組更改爲向量,並將任何其他具有'new'的指針分配給智能指針。內存將自動解除分配。 – chris

+0

@chris,我沒有創建任何數組 –

+0

請確保您有一個析構函數,其中在堆上的構造函數創建的所有實例在最後都被釋放並釋放。 –

回答

3

通行證-g選項gccg++讓你的可執行文件中都有調試符號。下面是使用-g在二進制文件上運行valgrind的示例。

==20538== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1 
==20538== at 0x4A05809: malloc (vg_replace_malloc.c:149) 
==20538== by 0x4004F7: main (test.c:8) 
==20538== 
==20538== LEAK SUMMARY: 
==20538== definitely lost: 4 bytes in 1 blocks. 
==20538==  possibly lost: 0 bytes in 0 blocks. 
==20538== still reachable: 0 bytes in 0 blocks. 
==20538==   suppressed: 0 bytes in 0 blocks. 
==20538== Reachable blocks (those to which a pointer was found) are not shown. 
==20538== To see them, rerun with: --show-reachable=yes 

gcc -g test.c 

這樣你就可以看到分配的線。

+0

我這樣做了,但它不起作用:( –

+1

@ l19 Loader類的源文件是在同一個版本中編譯和鏈接的嗎?這很奇怪,你可以創建一個簡單的程序(總是會泄漏內存)並查看如果valgrind能夠在您的環境中報告確切的行號# – Gant