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