简体   繁体   中英

2-Dimensional array deallocation

As an intro, I'm using C++ in Visual Studio 2010, compiling for x64. I have a program that's using 2-Dimensional arrays to store data for running through a C style function that I have no control over:

float **results;
results = new float*[rows];
for (int i = 0; i < rows; ++i){
    results[i] = new float[columns];
}

int **data;
data = new int*[rows];
for (int i = 0; i < rows; ++i){
    data[i] = new int[columns];
}

//send data to the function and populate results with values
ExternalFunction(*data, *results);

//delete everything
for (int i = 0; i < rows-1; ++i){
    delete [] &results[i];
    delete [] &data[i];
}
delete [] results;
delete [] data;

This causes VS10 to through a Debug Assertion Failure with _BLOCK_TYPE_IS_VALID(pHead -> nBlockUse). This happens by the end of the program regardless of what really happens in the last few lines containing the deletes. What does this mean exactly? What am I doing wrong? I feel like it's really simple, but I've been looking at this code for too long.

--EDIT--- Problem solved thanks to dasblinkenlight's helpful nudge to my brain!

float *results = new float[rows * columns];
float *data = new float[rows * columns];

ExternalFunction(&data[0], &results[0]);

delete [] results;
delete [] data;

Your code crashes because you are passing an address of an address to delete[] , which is not what you allocated. Change your code to this:

for (int i = 0; i < rows ; ++i){
    delete [] results[i];
    delete [] data[i];
}

It will no longer crash.

The rule on this is simple: since you assigned the results of new[..] to results[i] , you should be passing results[i] , not &results[i] , to delete [] . Same goes for data .

Also note that this code deletes all rows that you allocated, including the last one (the loop condition is now i < n , not i < n-1 ). Thanks bjhend!

You could use below as a macro or some delete function for 2D array with row count predefined :

for_each(results, results + rows , [](int* row) { delete[] row; });
delete[] results;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM