0

I have used pointers to create an array and then wrote a delete procedure in the destructor

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; }
    ...
   }

In another class I use cBuffer like this:

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

However, valgrind complains about the new operator

==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) 
4

2 回答 2

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

你需要打电话

delete buf;

由于您明确调用new

于 2013-04-28T14:50:56.643 回答
1

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

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

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

于 2013-04-28T14:50:33.263 回答