Delete a pointer to pointer (as array of arrays)

yelo3 picture yelo3 · Nov 16, 2010 · Viewed 38.7k times · Source

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;

?

Answer

Šimon T&#243;th picture Šimon Tóth · Nov 16, 2010

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.