2012-07-23 61 views
1

我寫了下面的代碼,以便對Valgrind有一個基本的瞭解,並且很難解釋它的輸出。這可能與Valgrind無關,但更多的是基本的C++。Understading Valgrind輸出

#include <string> 
#include <iostream> 
using namespace std; 

class Valgrind_testclass 
{ 
std::string * stringInHeap; 

public: 
    Valgrind_testclass() { 
    stringInHeap = new std::string("String in heap"); 
    } 
    ~Valgrind_testclass() { 
    //delete stringInHeap;     
    } 

    void PrintFunc(void) { 
    cout << "Nothing but a printout" << endl; 
    } 
}; 

int main() 
{ 
Valgrind_testclass * valObjPtr = new Valgrind_testclass(); 
delete valObjPtr;    
return 0; 
} 

Valgrind的輸出:

==4459== HEAP SUMMARY: 
==4459==  in use at exit: 31 bytes in 2 blocks 
==4459== total heap usage: 3 allocs, 1 frees, 35 bytes allocated 
==4459== 
==4459== Searching for pointers to 2 not-freed blocks 
==4459== Checked 102,100 bytes 
==4459== 
==4459== 31 (4 direct, 27 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2 
==4459== at 0x402641D: operator new(unsigned int) (vg_replace_malloc.c:255) 
==4459== by 0x80487DB: Valgrind_testclass::Valgrind_testclass() (in /home/madu/C++/ValgrindTest) 
==4459== by 0x80486F6: main (in /home/madu/C++/ValgrindTest) 
==4459== 
==4459== LEAK SUMMARY: 
==4459== definitely lost: 4 bytes in 1 blocks 
==4459== indirectly lost: 27 bytes in 1 blocks 
==4459==  possibly lost: 0 bytes in 0 blocks 
==4459== still reachable: 0 bytes in 0 blocks 
==4459==   suppressed: 0 bytes in 0 blocks 
==4459== 
==4459== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 17 from 6) 

可能有人請告訴我,我做3點的分配?我只能看到兩個分配。還有它爲什麼說「間接失落」?

謝謝。

回答

9

當您構造一個std::string對象時,它會分配另一個指針(對象內部)來指向字符串值。這是第三次分配的來源,也是間接泄漏的內存。

換句話說,你有這三個分配:

  1. new Valgrind_testclass()(明確的)
  2. new std::string("String in heap")(明確的)
  3. 字串內部分配(隱含/間接)

既然你泄漏了分配2,你也間接泄漏了分配3;字符串的析構函數將不會被調用,因此它沒有機會自由分配3.

+0

非常感謝。瞭解第三個分配來自哪裏。 – madu 2012-07-23 15:47:52

4

您有3個分配,因爲std::string也分配了內存。

間接丟失,意味着您丟失了指向其他內存指針的指針。在這種情況下,您並未刪除stringInHeap,並且您丟失了指針。通過這一點,分配內存的實際std::string無法刪除它,因此內存也丟失。

+0

非常感謝。我明白第三個指針實際在哪裏。 – madu 2012-07-23 15:49:15