tags:

views:

99

answers:

2
+1  Q: 

Cant free memory.

In code:

  template<class T,int row, int col>
void invert(T (&a)[row][col])
{
T* columns = new T[col * row];
T* const free_me = columns;
T** addresses = new T*[col * row];
T** const free_me_1 = addresses;
/*cpy addresses*/
for (int i = 0; i < row; ++i)
{
    for (int j = 0; j < col; ++j)
    {
        *addresses = &a[i][j];
        ++addresses;
    }
}
addresses = free_me_1;
/*cpy every column*/
for (int i = 0; i < col; ++i)
{
    for (int j = 0; j < row; ++j)
    {
        *columns = a[j][i];
        ++columns;
    }
}
columns = free_me;
/*cpy from columns to addresses*/
for (int i = 0; i < (col * row); ++i)
{
    *addresses[i] = columns[i];
}

delete[] free_me_1;
delete[] free_me;
}

I've observed that while iterating, value of variable columns equals zero and I think thats the problem.
Thanks for your help.

P.S. I've pasted final version of this fnc. It works as intended now. Thank you everyone for your valuable help.

+4  A: 

You write past the buffer end because the buffer is too small.

T* columns = new T[col];

should be

T* columns = new T[col*row];

Writine past the buffer end is undefined behavior - in your case it's heap corruption because you overwrite some service data essential for the heap functioning and so delete[] fails.

sharptooth
But at what point?
There is nothing we can do
Thanks, of course, I'm fecking eejit. I'll accept your answer in 10 mins;
There is nothing we can do
+1  A: 

You initialize columns as a new T[col]. Then you increment columns in the inner loop, which gets execute col*row times - unless rows==1, you increment columns past the end of the array you've allocated, causing undefined behaviour.


Note that even once you fix that, your function is still very wrong - it has neither a return value nor side effects. It should be a no-op. It definitely doesn't invert its parameter.

Joe Gauterin
Yes I know that, this is actually just some fragment of this fnc;
There is nothing we can do