33

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;

?

Community
  • 1
  • 1
yelo3
  • 5,613
  • 5
  • 26
  • 23

5 Answers5

32

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.

Šimon Tóth
  • 35,456
  • 20
  • 106
  • 151
21

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;
CB Bailey
  • 755,051
  • 104
  • 632
  • 656
19

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!
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
6

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).

Stephane Rolland
  • 38,876
  • 35
  • 121
  • 169
6

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> >.

icecrime
  • 74,451
  • 13
  • 99
  • 111