mahmood
mahmood

Reputation: 24795

Valgrind complains about a memory leak but I'm calling new and delete

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) 

Upvotes: 0

Views: 1610

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254701

Your class foo will cause your leak, since you never delete the dynamically allocated cBuffer. The solution is simple: there's no need for dynamic allocation at all here.

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

More generally, when you do need dynamic allocation, be careful that you always delete what you new. The most reliable way to do this is to use RAII types such as containers and smart pointers to manage all dynamic resources for you.

Upvotes: 1

Alok Save
Alok Save

Reputation: 206616

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

You need to call

delete buf;

Since you explicitly called new

Upvotes: 2

Related Questions