Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

De-allocate a 3D array

I'm working in C++ and I have to allocate a 3d array of doubles. This is the code used for the allocation:

cellMatrix = (double***)malloc(N*sizeof(double**));
if (cellMatrix == NULL)
{
    errorlog("Allocation Error -> CellMatric can't be created");
}
for (int k = 0; k < N; k++)
{
    cellMatrix[k] = (double**)malloc(M*sizeof(double*));

    if (cellMatrix[k] == NULL)
    {
        errorlog("Allocation Error -> *CellMatric can't be created");
    }
    for (int i = 0; i < M; i++)
    {
        cellMatrix[k][i] = (double*)malloc(B*sizeof(double));
        if (cellMatrix[k][i] == NULL)
        {
            errorlog("Allocation Error -> **CellMatric can't be created");
        }
    }
} 

The allocation doesn't have any problem. Finally, when I have to de-allocate the "cube" some issues occurred. This is the code:

for (int i = 0; i < N; i++)
{
    for (int j = 0; j < M; j++)
    {
        free(cellMatrix[i][j]);
    }
    free(cellMatrix[i]);
}
free(cellMatrix);

The program stops during the deallocation of cellMatrix[i], printing this error message (Visual Studio Pro '13)

HOG.exe has triggered a breakpoint.

Can someone help me with this issue?

like image 852
SR_ Avatar asked Apr 13 '26 04:04

SR_


1 Answers

From your error message, I suspect you're running in Debug mode and have (inadvertently) set a breakpoint at the free(cellMatrix[i])); line.

Following Wyzard's suggestion, you could allocate a contiguous array with

double cellArray[] = new double[N*M*B];

and index into it with

double& cell(int i, int j, int k) { return cellArray[i + j*N + k*N*M]; }
like image 75
Matt Olson Avatar answered Apr 14 '26 17:04

Matt Olson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!