简体   繁体   中英

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) 
 cBuffer *buf;
   foo()
   {
     buf = new cBuffer(gSize, oDist, Mode);
   }

You need to call

delete buf;

Since you explicitly called new

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM