Delete a pointer to pointer (as array of arrays)

42,128

Solution 1

Simple rules to follow:

  • for each allocation, there has to be a deallocation (ex1 is therefore wrong)
  • what was allocated using new should be freed using delete, using new[] should be deallocated using delete[] and using malloc should be deallocated using free (ex3 is therefore wrong)

Conclusion, ex2 is OK.

Solution 2

Your code shouldn't compile. The type of an array new expression is a pointer to the type of array element being created (the value is a pointer to the first element of the allocated array).

So the type of new double**[size_out] is double ***.

Whenever you use the array form of new, you must use the array form of delete even if you only allocate an array of size one.

double*** desc = new double**[size_out];
for (int i=0; i<size_out; i++)
    desc[i] = new double*[size_in];


for (int i=0; i<size_out; i++)
    delete[] desc[i];

delete[] desc;

Note that you still haven't allocated any double, just pointers.

Did you really want this instead?

double** desc = new double*[size_out];
for (int i=0; i<size_out; i++)
    desc[i] = new double[size_in];

for (int i=0; i<size_out; i++)
    delete[] desc[i];

delete[] desc;

Solution 3

Your deletion should mirror your allocation.

Since you used new [] to allocate the outer array, and new [] (in a loop) to allocate the inner arrays, do likewise for deletion. That is: your second solution is correct; delete [] the inner arrays in a loop, and finally the outer array via delete [] also.

That said, a (much, much) better solution in C++ would be to use a nested std::vector:

// Declaration and initialization:
vector<vector<double> > desc(size_out, vector<double>(size_in));

// No deletion!

Solution 4

Solution 2 is the right one : each cell points to a dynamically allocated array that should be deleted using delete[]. Finally, the desc array itself should be deleted using delete[].

Bonus solution 4 : avoid using arrays and switch to std::vector<std::vector<double> >.

Solution 5

I would do

for (int i=0; i<size_out; i++)
    delete [] desc[i];
delete [] desc;

for each array allocated with new [], you have a corresponding delete [].

And as Rupdolph says: stop using C-arrays, and start using std::vector. You will have less bugs (hundred times less bugs).

Share:
42,128
yelo3
Author by

yelo3

Updated on April 01, 2020

Comments

  • yelo3
    yelo3 about 4 years

    I have this in my code:

    double** desc = new double* [size_out];
    for (int i = 0; i < size_out; i++)
        desc[i] = new double [size_in];
    

    How do I delete this desc?

    Should I do:

    delete [] desc;
    

    or

    for (int i=0; i<size_out; i++)
        delete [] desc[i];
    delete [] desc;
    

    or

    for (int i=0; i<size_out; i++)
        delete [] desc[i];
    delete desc;
    

    ?