Error while tranposing a dynamic array

Hello, so here below is a void function that transposes a dynamic array.

It works for some inputs that I try but for other inputs I insert I get this warning:

TRANS(41432,0x7fff74a20000) malloc: *** error for object 0xa000000000000000: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug

It seems like there is some memory leak but I´m new in c++ programming and can´t figure out what it is that I need to fix. Do you have any tips ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  void transpose(int** &arr, int &row, int &col)
{
    int **tmp=new int *[col];
    for(int i=0; i < col; i++)
    {
        tmp[i]=new int[row];

    }
    for(int i=0; i < col; i++)
    {
        for (int j=0; j< row; j++)
        {

            tmp[i][j]=arr[j][i];
        }
    }

    delete[] arr;
    arr = tmp;
    
}


Last edited on
You need to delete the memory in the reverse order from what you allocated the memory. In this case you need to use a loop to delete tmp[] then you must delete[] *arr.

I tried this:

for(int i=0; i < col; i++)
delete[] tmp[i];

delete[] arr;
arr = tmp;

but it did not work
Why didn't it work? If you got error messages post them.

Topic archived. No new replies allowed.