Reputation: 3
I have a problem with two dimensional dynamically allocated array I'm using in my code. Everything works fine until my program tries to call the destructor of my tablica2D
object. I get a runtime error "HEAP CORRUPTION DETECTED" when my program gets to the last delete[] tab
command. Does this mean that the loop preceding it already deallocates all of memory assigned to tab
? I was under the impression that to deallocate all of dynamically assigned memory there needs to be one delete
command for each new
command. Or is something else causing this error?
Here is the code of the class that's causing me trouble:
class tablica2D
{
static const int k = 2;
int n, m;
string **tab;
public:
tablica2D(int n, int m)
{
this->n = n;
this->m = m;
tab = new string*[n];
for (int i = 0; i < m; i++)
{
tab[i] = new string[m];
}
}
string* operator [](int n)
{
return tab[n];
}
static const bool compareRows(const string* i, const string* j)
{
int x = atoi(i[k].c_str());
int y = atoi(j[k].c_str());
return x > y;
}
void sort()
{
std::sort(tab, tab + n, compareRows);
}
~tablica2D()
{
for (int i = 0; i < n; i++)
{
delete[] tab[i];
}
delete[] tab;
}
};
Upvotes: 0
Views: 1551
Reputation: 302718
You are using the wrong variable in your new
loop, and additionally creating a 3d array instead of a 2d array:
for (int i = 0; i < m; i++)
// ^^, should be n
{
tab[i] = new string[m];
// ^^^
// should be new string, not new string[m]
}
vs:
for (int i = 0; i < n; i++)
// ^^, this one is correct
{
delete[] tab[i];
}
Upvotes: 2
Reputation: 13988
If I need a C-like 2D array I always use:
type **myarr = new type*[X];
myarr[0] = new type[X*Y];
for (int i = 1; i < X; i++) {
myarr[i] = myarr[0] + i * Y;
}
For usage:
myarr[x][y]
Then for freeing:
delete[] myarr[0];
delete[] myarr;
The same, with some little effort, can be applied for N-dimentional array.
Upvotes: 0