double free 或 corruption (out) 以及如何检查析构函数是否正常工作
我正在尝试改进我的二维数组 使用类创建.所有方法都工作正常,它被正确打印出来等等,但是当我尝试创建一个析构函数时,我要么得到一个错误double free or corruption
,我能够摆脱错误消息,但是那么我不确定内存是否已正确解除分配,因为我使用了两个 new
关键字但只有一个 delete
.
I am trying to improve my 2D array to be created using a class. All methods work fine, it is properly printed out and so on, but when I try to create a destructor I either get an error double free or corruption
, I am able to get rid of the error message but then I am not sure whether the memory has been de-allocated properly, because I am using two new
keywords but only one 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 方式.
I know that this is performance-wise slower solution (heap allocation), I tried to use std::vector way.
非常感谢您的帮助
您的构造函数分配了一个大小为 rows
(3) 的顶级数组,然后继续填充 slots代码>(10)元素吧:
Your constructor allocates a top-level array of size rows
(3) but then goes on to fill slots
(10) elements of it:
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
或 Memory sanitizer 下运行你的代码,这个错误应该立即突出.
As cell
only holds 3 elements, the 7 allocations after firmly corrupt the heap by writing past allocated memory. If you run your code under valgrind
or Memory sanitizer, this error should immediately stand out.