当我用 Xcode 编译并运行它时,我得到错误,至少连续 100 次,malloc: *** error for object 0x100180: double free
,调试器指向C 行
。奇怪的是,在我从中提取的代码中,出现了完全相同的错误,但调试器指向了 line B
的等效项。我试过了,但无法重现。
如果我删除 line A
,该代码可以运行,但我会遇到严重的内存泄漏,该泄漏会在大约 1 分钟内使程序崩溃。删除 line C
可以解决问题,但不是有效的解决方案,因为 a_class
没有合适的析构函数。
#include <iostream>
#include <vector>
struct a_struct
{
int* dynamic_array;
a_struct(int length) {dynamic_array = new int [length];}
a_struct() : dynamic_array(NULL) {}
~a_struct() { if (dynamic_array != NULL) {delete [] dynamic_array;} } //Line A
};
class a_class
{
public:
a_struct* the_structs;
a_class() {Init();}
a_class(a_class const & origin) {Init();}
void Init(){
the_structs = new a_struct [10]; //Line B
for(int q=0; q<10; q++)
the_structs[q] = a_struct(7);}
~a_class() { if (the_structs != NULL) {delete [] the_structs;} } //Line C
};
int main ()
{
std::vector <a_class> the_objects;
for(int q=0; q<10; q++)
the_objects.push_back(a_class());
while(1)
for(int q=0; q <10; q++)
for(int w=0; w <10; w++)
the_objects[q].the_structs[w] = a_struct(7);
}
最佳答案
修复 a_struct 和 a_class 以具有正确的复制构造函数和赋值运算符。有问题再回来。
确保你所有的类总是遵循The Rule of 3 .我最近似乎经常链接到那个页面。
关于c++ - 尝试处理嵌套对象/结构和动态数组时发生内存泄漏或内存错误。可能的 Xcode/malloc 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6728571/