2-Dimensional array deallocation

16,769

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!

Share:
16,769
user850275
Author by

user850275

Updated on June 04, 2022

Comments

  • user850275
    user850275 almost 2 years

    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;