Insano
Insano

Reputation:

Is this deallocation correct?

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]

Upvotes: 4

Views: 6326

Answers (6)

Dima
Dima

Reputation: 39389

The way you have it, you should :

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

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).

// allocate
int **matrix = new int*[3];
for(int i = 0; i &lt 3; ++i)
  matrix[i] = new int[3];

// deallocate
for(int i = 0; i &lt 3; ++i)
  delete [] matrix[i];

delete [] matrix;

Upvotes: 8

Fred Larson
Fred Larson

Reputation: 62053

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:

int* matrix = new int[3*3];

for (int i = 0; i < 3; ++i)
    for (int j = 0; j < 3; ++j)
        matrix[i*3+j] = x;

delete [] matrix;

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.

Upvotes: 4

bk1e
bk1e

Reputation: 24328

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.

Upvotes: 1

anon
anon

Reputation:

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.

Upvotes: 6

mfawzymkh
mfawzymkh

Reputation: 4108

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

Upvotes: -1

kmarsh
kmarsh

Reputation: 1398

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

Upvotes: 6

Related Questions