[英]Valgrind complains about a memory leak but I'm calling new and delete
我使用指針創建一個數組,然后在析構函數中編寫了一個刪除過程
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)
cBuffer *buf;
foo()
{
buf = new cBuffer(gSize, oDist, Mode);
}
你需要打電話
delete buf;
既然你明確地叫了new
你的class foo
會導致泄漏,因為你永遠不會刪除動態分配的cBuffer
。 解決方案很簡單:這里根本不需要動態分配。
class foo {
cBuffer buf; // An object, not a pointer
foo() : buf(gSize, oDist, Mode) {}
};
更一般地說,當您需要動態分配時,請注意始終delete
new
。 最可靠的方法是使用容器和智能指針等RAII類型來管理所有動態資源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.