我正在尝试改进使用类创建的2D数组。所有方法都能正常工作,它被正确地打印出来,等等,但当我试图创建析构函数时,我要么得到一个错误double free or corruption
,我可以摆脱错误消息,但我不确定内存是否被正确地取消分配,因为我使用了两个new
关键字,但只有一个delete
。
这是我的班级申报单:
#pragma once
class myPlan
{
int slots;
int rows = 3;
int **cell;
public:
myPlan(int slots); // Constructor
~myPlan();
};
这里是的定义
#include "myPlan.hpp"
myPlan::myPlan(int slots)
{
this->slots = slots;
// Create a dynamic array of pointers
cell = new int* [rows];
// Create a row for every pointer
for (int i=0; i<slots; i++)
{
cell[i] = new int[slots];
}
for(int i =0; i<3; i++)
{
for (int j=0; j<slots; j++)
{
cell[i][j] = 0; //setting all cells to zero
}
}
}
//this destructor works
myPlan::~myPlan()
{
std::cout<<"preparing for destruction"<<std::endl;
delete[] cell;
std::cout<<"Destroyed class"<<std::endl;
}
//this returns the double free error
/*
myPlan::~myPlan()
{
for(int i = 0; i < rows; ++i)
{
delete[] cell[i];
}
delete[] cell;
}
*/
我知道这是性能方面较慢的解决方案(堆分配(,我尝试使用std::vector的方式。
非常感谢您对的帮助
您的构造函数分配了一个大小为rows
(3(的顶级数组,然后继续填充其中的slots
(10(元素:
cell = new int* [rows];
// Create a row for every pointer
for (int i=0; i<slots; i++)
{
cell[i] = new int[slots];
}
由于cell
只包含3个元素,因此之后的7个分配通过写入已分配的内存来稳固地破坏堆。如果您在valgrind
或内存清理程序下运行代码,这个错误应该会立即突出。