2010-01-28 84 views
3

今天我只是想检查valgrind是如何工作的。所以我创建了一个简单的程序。意外的内存泄漏[Valgrind]

//leak.C 
#include<iostream> 

class leak 
{ 

    int *p; 

    public: 

    leak():p(new int[10]()){std::cout<<"Constructor of leak called\n";} 
    virtual void set() 
    { 

     for(int i=0;i<10;++i) p[i]=i*i; 
    } 

    virtual void display() 
    { 
     std::cout<<"In leak's display()\n"; 
     for(int i=0;i<10;++i) std::cout<<p[i]<<std::endl; 
    } 

    virtual ~leak() 
    { 
     std::cout<<"Destructor of leak called\n"; 
     delete[] p; 
    } 
}; 

class exleak: public leak 
{ 

    double *r; 

    public: 

    exleak():r(new double[5]()){std::cout<<"Constructor of exleak called\n";} 

    void set() 
    { 
     leak::set(); 
     for(int i=0;i<5;i++) r[i]=i*3.0; 
    } 


    void display() 
    { 
     leak::display(); 
     std::cout<<"In exleak's display()\n"; 
     for(int i=0;i<5;i++) std::cout<<r[i]<<std::endl; 
    } 

    ~exleak() 
    { 

      std::cout<<"Destructor of exleak called\n"; 
      delete[] r; 
    } 
}; 

int main() 
{ 

    leak *x=new exleak(); 
    x->set(); 
    x->display(); 
    delete x; 

} 

产量如预期。我预计没有内存泄漏。 我编译了文件leak.C并生成了可执行文件leak。 但是当我输入以下命令valgrind --leak-check=yes --verbose ./leak时,我很惊讶。该代码有内存泄漏。 :-o

这就是我得到的。

==9320== 
==9320== HEAP SUMMARY: 
==9320==  in use at exit: 12 bytes in 1 blocks 
==9320== total heap usage: 3 allocs, 2 frees, 92 bytes allocated 
==9320== 
==9320== 12 bytes in 1 blocks are definitely lost in loss record 1 of 1 
==9320== at 0x40263A0: operator new(unsigned int) (vg_replace_malloc.c:214) 
==9320== by 0x8048B0E: main (in /home/prasoon/leak) 
==9320== 
==9320== LEAK SUMMARY: 
==9320== definitely lost: 12 bytes in 1 blocks 
==9320== indirectly lost: 0 bytes in 0 blocks 
==9320==  possibly lost: 0 bytes in 0 blocks 
==9320== still reachable: 0 bytes in 0 blocks 
==9320==   suppressed: 0 bytes in 0 blocks 
==9320== 
==9320== For counts of detected and suppressed errors, rerun with: -v 
==9320== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 25 from 6) 

代码是如何泄漏内存的?

definitely lost: 12 bytes in 1 blocks //WHERE? 

编辑物质解决

+0

你可以尝试与leak-check = full,也许它会给更多的信息 – 2010-01-28 07:16:46

+0

我的坏,可能我那时犯了一个错误。我再次编译了代码,再次生成可执行文件。现在没有内存泄漏。 :-) – 2010-01-28 07:21:56

+0

是的,我也试过了(没有看到“问题解决”)。 valgrind没有报告泄漏。 – 2010-01-28 11:00:44

回答

-1

类exleak没有虚析构函数...

+0

但基类有... – 2010-01-28 07:09:39

+0

那么,它在这里有什么关系?如果'leak'的析构函数不是虚拟的,情况就会不同。 – 2010-01-28 07:11:15

2

我2.6.18-164.11.1.el5内核和GCC 4.1.2试了一下在Linux上,它并没有给我任何泄漏

我没有看到任何问题的代码