[英]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: 在另一个类中,我使用cBuffer,如下所示:
class foo() {
cBuffer *buf;
foo()
{
buf = new cBuffer(gSize, oDist, Mode);
}
};
However, valgrind complains about the new operator 然而,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)
cBuffer *buf;
foo()
{
buf = new cBuffer(gSize, oDist, Mode);
}
You need to call 你需要打电话
delete buf;
Since you explicitly called new
既然你明确地叫了
new
Your class foo
will cause your leak, since you never delete the dynamically allocated cBuffer
. 你的
class foo
会导致泄漏,因为你永远不会删除动态分配的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
. 更一般地说,当您需要动态分配时,请注意始终
delete
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. 最可靠的方法是使用容器和智能指针等RAII类型来管理所有动态资源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.