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?
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]; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With