阅读后: C++ Array of pointers: delete or delete []? (由shai vashid回复) 和 http://www.cplusplus.com/forum/beginner/6651/
我实施了以下内容:
kernel.h当
unsigned int **ConfigMeM;
//.....
~Kernel(){ //destructor
for (unsigned int i=0; i<MeMSize; i++)
delete [] MeM[i]; //Valgrind:- Invalid read of size 4
- Invalid free() / delete / delete[] / realloc()
delete [] MeM; //Valgrind: Invalid free() / delete / delete[] / realloc()
for (unsigned int i=0; i<_item_tot; i++)
delete [] ConfigMeM[i]; //Valgrind: Same comments as above
delete [] ConfigMeM; //Valgrind: same as above
};
Kernel.cpp
//.......
MeM = new unsigned int*[MeMSize];
for (unsigned int i=0; i<MeMSize; i++){
MeM[i] = new unsigned int[11]; //Valgrind: 14,608 bytes in 332 blocks are definitely lost in loss record 2,021 of 2,036
}
for (unsigned int i=0; i<MeMSize; i++){
for (int j=0; j<10; j++){
MeM[i][j] = 0;
}
}
//.....
ConfigMeM = new unsigned int*[_item_tot];
for (unsigned int i=0; i<_item_tot; i++){
ConfigMeM[i] = new unsigned int[3]; //Valgrind: 1,200 bytes in 100 blocks are definitely lost in loss record 1,131 of 2,036
}
for (unsigned int i=0; i<_item_tot; i++){
for (int j=0; j<3; j++){
ConfigMeM[i][j] = 0;
}
}
//.....
我不确定我做错了什么。
有什么建议吗?
谢谢。
答案 0 :(得分:1)
我最好的猜测是使用隐式生成的复制构造函数或复制赋值运算符复制类的对象。这将留下两个带有指向同一内存的对象;两者都会尝试在销毁时删除此内存,从而导致双删除错误。
最简单的解决方法是通过删除这些功能来阻止复制:
Kernel(Kernel const&) = delete;
void operator=(Kernel const &) = delete;
或者,如果您使用古老的编译器,请将它们声明为私有而没有函数体。
如果你需要复制这些对象,那么你需要实现这些对象,或许是为了执行一个深层复制&#34;分配新的内存块。
或者,使用std::vector
管理动态数组可能更容易;这已经具有正确的复制语义,并且可以非常简单地初始化:
std::vector<std::vector<unsigned int>> MeM, ConfigMem;
(MemSize, std::vector<unsigned int>(11));