aratn0n aratn0n - 2 months ago 19
C++ Question

Deleting 3d dynamic array C++

I make a 3d dynamic array by this using this code

//layer = 2

//levelSize.x = 100

//levelSize.y = 100

level_array = new int**[layer];

for(int i = 0; i < layer; ++i)
{
level_array[i] = new int*[(int)levelSize.x];
for(int j = 0; j < levelSize.x; ++j)
level_array[i][j] = new int[(int)levelSize.y];
}


but when I want to delete it, the program crashes

for(int i = 0; i != levelSize.x; ++i)
{
for(int j = 0; j != levelSize.y; ++j)
{
delete[] level_array[i][j];
}
delete[] level_array[i];

}
delete[] level_array;


I don't know where is wrong in the code of deleting an array.

Please help me check the code, Thanks

Answer

You allocate memory for array with dimensions [layer][levelSize.x][levelSize.y], but while deleting you operate with it like with array with dimensions [levelSize.x][levelSize.y][somenting].

for(int i = 0; i != layer; ++i)
//                  ^^^^^ not levelSize.x
{
    for(int j = 0; j != levelSize.x; ++j)
    //                  ^^^^^^^^^^^ not levelSize.y
    {
        delete[] level_array[i][j];
    }
    delete[] level_array[i];

}
delete[] level_array;
Comments