5

I defined:

A** mat = new A*[2];

but how can I delete it? With delete[] mat; or delete[] *mat;?

Liam Marshall
  • 1,353
  • 1
  • 12
  • 21
Alon Shmiel
  • 6,753
  • 23
  • 90
  • 138
  • 4
    This is exactly what RAII is good for. You wouldn't have to worry about freeing it. – chris May 29 '13 at 01:33
  • Use a container (smart pointer type) or write a small wrapper yourself, overloading `operator()` (as pointed out by chris below, I had initially recommended `operator[]`) – 0xC0000022L May 29 '13 at 01:35
  • @0xC0000022L, `operator()` is a better choice tbh. – chris May 29 '13 at 01:37
  • @chris, fair point ... for multi-dimensional arrays it certainly is :) – 0xC0000022L May 29 '13 at 01:38
  • 1
    @0xC0000022L, Yeah, and to expand on your point, you can still use a 1D RAII container to implement it :) – chris May 29 '13 at 01:38
  • Similar: http://stackoverflow.com/questions/14829597/free-allocated-memory-in-2d-dynamic-memory-allocation-array-in-c – chris May 29 '13 at 01:43

2 Answers2

7

It's delete[] mat; only when you do not do additional allocations. However, if you allocated the arrays inside the array of arrays, you need to delete them as well:

A** mat = new A*[2];
for (int i = 0 ; i != 2 ; i++) {
    mat[i] = new A[5*(i+3)];
}
...
for (int i = 0 ; i != 2 ; i++) {
    delete[] mat[i];
}
delete[] mat;
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    Good answer but its not just for 2D arrays. He could have an array of pointer to A with allocated memory (`mat[i] = new A();`) which would need a `delete mat[i];` call instead of `delete [] mat[i];`. But you got it close enough :) – Sellorio May 29 '13 at 02:07
2

the first one, delete[] mat

the second one would delete what the first element in the array was pointing to (which would be nothing if that is really all the code you have) it is equivalent to delete [] mat[0]

also, if the pointers in the array did end up pointing to allocated memory that you also wanted freed, you would have to delete each element manually. eg:

A** mat = new A*[2];
mat[0] = new A;
mat[1] = new A[3];

then you would need to do:

delete mat[0];
delete[] mat[1];
delete[] mat;
matt
  • 4,042
  • 5
  • 32
  • 50
  • 1
    I want to upvote you just because your username is matt. i.e. see matt's comment that `A** mat` should be de-allocated using `for() delete[] mat[i];` and `delete[] mat;`. Got it @matt? – axon May 29 '13 at 02:45
  • If you wrote that allocation code in the first place you'd also need to resign from your job... – M.M Jul 07 '15 at 22:07