So I'm used to memory management in C where free(pointer)
will free up all space pointed to by pointer
. Now I'm confusing myself when attempting to do something simple in C++.
If I have a 2D array of doubles allocated in a manner similar to this
double** atoms = new double*[1000];
for(int i = 0; i < 1000; i++)
atoms[i] = new double[4];
what would be the correct method of freeing the memory on the heap allocated by new?
My thoughts were originally this (because my brain was thinking in C):
for(int i = 0; i < 1000; i++)
delete atoms[i];
delete atoms;
But I had forgotten the existence of the delete[]
operator so I believe the correct method is as follows:
for(int i = 0; i < 1000; i++)
delete[] atoms[i];
delete[] atoms;
Is it important to understand the difference between the delete
and delete[]
operators? Or can I just assume that whenever I allocate an array with ptr = new x[]
I must also deallocate it with delete[] ptr
?
delete []
is valid. If you calldelete []
for non array object, it is an ub. You can see in other SO questions: https://mcmap.net/q/16878/-delete-vs-delete-duplicate – Cleliaclellan