2012-07-23 59 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