I've a 3x3 2D dynamic array allocated as below:
int** matrix = new int* [3];
matrix[0] = new int [3*3];
for (int i = 1; i < 3; ++i)
matrix[i] = matrix[i-1] + 3;
How should I deallocate it? Is this correct:
delete [] matrix;
delete [] matrix[0];
Or should I also delete matrix[1]
, [2]
You'll need one delete for each new, in reverse order of the new's.
Every element in the matrix array is an int[], in addition to that, matrix itself is an array of int* (int*[]), taking these rules into account you should do
delete [] matrix[i] { i=0,1,2 }
and then do delete [] matrix to delete the matrix itself.
Hope this helps. Thanks
The way you have it, you should :
But this is a very unconventional way of allocating a dynamic 2D array. Normally you allocate an array of pointers, and then you allocate an array of your actual type for every row (column).
You need to read this: http://isocpp.org/wiki/faq/freestore-mgmt#multidim-arrays
In a nutshell, allocate your matrix in a single chunk if it is rectangular:
Since it's allocated in one chunk you can also delete in one chunk.
Or you can do something similar to what you're doing, but do an allocation for each row. Be sure to delete each row first, then the matrix.
The linked article also has info about wrapping up the nasty pointer/array stuff in a class.
The code:
is obviously wrong, as you use matrix after you delete it.
is correct, but I can't vouch that the code as whole does something sensible.
Note that you should not delete matrix[1] and matrix[2] as they are just copies of matrix[0]. A rule of thumb is that you should have the same number of calls to delete as you have calls to new.
The array of pointers may be unnecessary. You could just allocate the 1D array of 9 elements and do the math to convert 2D indexes to 1D indexes.
In addition to swapping around the
delete[]
operations, you should consider what happens when an allocation fails. If the second allocation throwsstd::bad_alloc
, your program leaks the memory from the first allocation. A correctly-written matrix class (as suggested by Fred Larson) would handle memory deallocation for you.