问题
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
.
Here is my class declaration:
#pragma once
class myPlan
{
int slots;
int rows = 3;
int **cell;
public:
myPlan(int slots); // Constructor
~myPlan();
};
and here is definition
#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;
}
*/
I know that this is performance-wise slower solution (heap allocation), I tried to use std::vector way.
Thank you very much for any help
回答1:
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];
}
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.
来源:https://stackoverflow.com/questions/64168457/double-free-or-corruption-out-and-how-to-check-whether-a-destructor-works-prop