Valgrind抱怨内存泄漏,但我正在调用new并删除

时间:2013-04-28 14:35:56

标签: c++ memory-leaks valgrind

我使用指针创建一个数组,然后在析构函数中编写了一个删除过程

class cBuffer{
  private:
    struct entry {
      uint64_t key;
      uint64_t pc;
    };
    entry *en;
  public:
    cBuffer(int a, int b, int mode)
    {
      limit = a;
      dist = b;
      md = mode;
      en = new entry[ limit ];
      for (int i=0; i<limit; i++) {
        en[i].key = 0;
        en[i].pc = 0;
      }
    };
    ~cBuffer() { delete [] en; }
    ...
   }

在另一个课程中我使用cBuffer:

class foo() {
   cBuffer *buf;
   foo()
   {
     buf = new cBuffer(gSize, oDist, Mode);
   }
};

然而,valgrind抱怨新的运营商

==20381== 16,906,240 bytes in 32 blocks are possibly lost in loss record 11,217 of 11,221
==20381==    at 0x4A0674C: operator new[](unsigned long) (vg_replace_malloc.c:305)
==20381==    by 0x166D92F8: cBuffer::cBuffer(int, int, int) 

2 个答案:

答案 0 :(得分:2)

 cBuffer *buf;
   foo()
   {
     buf = new cBuffer(gSize, oDist, Mode);
   }

您需要致电

delete buf;

由于您明确调用了new

答案 1 :(得分:0)

您的class foo会导致泄密,因为您永远不会删除动态分配的cBuffer。解决方案很简单:这里根本不需要动态分配。

class foo {
    cBuffer buf;  // An object, not a pointer
    foo() : buf(gSize, oDist, Mode) {}
};

更一般地说,当您需要动态分配时,请注意始终delete new。最可靠的方法是使用RAII类型(如容器和智能指针)来管理所有动态资源。