Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

c++ - 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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...