1

I can't delete the dynamically generated arrays. There is how I create them:

template <typename T>
T **AllocateDynamic2DArray(int nRows, int nCols){
      T **dynamicArray;

      dynamicArray = new T*[nRows];
      for( int i = 0 ; i < nRows ; i++ ){
        dynamicArray[i] = new T[nCols];
        for ( int j=0; j<nCols;j++){
                dynamicArray[i][j]= 0;
            }
        }
      return dynamicArray;
}

And I initialize a 2D array using:

long double** h = AllocateDynamic2DArray<long double>(KrylovDim+1,KrylovDim);

I can't delete it. Here are the variations that I've tried:

delete[] h;

and it gives the error: "cannot delete objects that are not pointers" when I apply this:

   for (int qq=0; qq < KrylovDim+1; qq++){
        for (int ww=0; ww < KrylovDim; ww++){
            delete [] h[qq][ww];
        }
        delete [] h[qq];
    }

Is there any way for a clean delete? I'm using visual studio 2010 if it helps.

1
  • Easy way to figure this out: you must have exactly one (not more, not fewer) delete, for every new. In your allocation, you invoke new 1+nRows times. How many times do you invoke delete? Commented Apr 29, 2011 at 19:07

1 Answer 1

4

Try this:

for (int qq=0; qq < KrylovDim + 1; qq++)
{
    delete [] h[qq];
}
delete [] h;

So basically you are doing the reverse of the allocation process

for( int i = 0 ; i < nRows ; i++ ){
    dynamicArray[i] = new T[nCols]; // Instead of allocating now delete !
Sign up to request clarification or add additional context in comments.

3 Comments

@Emre np. Sorry for the multiple edits but I was juggling somethings at the same time :)
R: so you start deleting by the outermost dimension? if it was a 4D array, we would have 3 loops to delete and 1 delete[] h. cool.
@Emre yup... basically just do the exact reverse of the allocation process.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.