Is this deallocation correct?

2020-06-22 04:20发布

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]

6条回答
2楼-- · 2020-06-22 04:41

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

查看更多
叼着烟拽天下
3楼-- · 2020-06-22 04:43

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

查看更多
不美不萌又怎样
4楼-- · 2020-06-22 04:45

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;
查看更多
贼婆χ
5楼-- · 2020-06-22 04:57

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.

查看更多
该账号已被封号
6楼-- · 2020-06-22 05:01

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.

查看更多
来,给爷笑一个
7楼-- · 2020-06-22 05:01

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.

查看更多
登录 后发表回答