Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

free the memory of: A** mat = new A*[2];

I defined:

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

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

like image 370
Alon Shmiel Avatar asked May 29 '13 01:05

Alon Shmiel


2 Answers

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;
like image 110
Sergey Kalinichenko Avatar answered Oct 09 '22 07:10

Sergey Kalinichenko


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;
like image 42
matt Avatar answered Oct 09 '22 08:10

matt