tags:

views:

435

answers:

6

Hello,

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 it correct:

delete [] matrix;

delete [] matrix[0];

Or should I also delete matrix[1], [2]

Greetings,

+4  A: 
Dima
+1 first useful answer
Binary Worrier
Actually, that's a pretty common way to allocate a 2D array. It ensures that all the data in the matrix is contiguous in memory and, for sufficiently large matrices, is more efficient.
eduffy
Actually, using a matrix wrapper as pointed by @Fred Larson, is more idiomatic than allocating an array of pointers into a 1D array.
David Rodríguez - dribeas
+5  A: 

You'll need one delete for each new, in reverse order of the new's.

kmarsh
+5  A: 

The code:

delete [] matrix;
delete [] matrix[0];

is obviously wrong, as you use matrix after you delete it.

delete [] matrix[0];
delete [] matrix;

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.

anon
A: 

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

mfawzymkh
why the negative vote!
mfawzymkh
What is "delete [] matrix[i] { i=0,1,2 }" supposed to be?
bk1e
well, I was writing it in a mathimatical condensed form, it means for i = 0, 1 and 2. Since the matrix is 3 elements, so instead of writing a for loop, I wrote it in this form.Thanks
mfawzymkh
+3  A: 

You need to read this: http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.16

Fred Larson
A: 

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 throws std::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.

bk1e