Is this liberation right?

I have a 3x3 2D dynamic array highlighted 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 can I free him? Is it correct:

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

Or also I have to remove matrix[1] , [2]

+4
source share
6 answers

As you have this, you should:

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

But this is a very unconventional way to allocate a dynamic 2D array. Usually you allocate an array of pointers, and then you allocate an array of your actual type for each 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; 
+8
source

You will need one deletion for each new, in the reverse order of the new.

+6
source

Code:

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

obviously wrong because you are using the matrix after removing it.

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

is correct, but I cannot guarantee that the code as a whole does something reasonable.

Please note that you should not delete matrix [1] and matrix [2], since they are only copies of matrix [0]. A rule of thumb is that you must have the same number of calls to delete, since you have calls for new ones.

+6
source

You need to read the following: http://isocpp.org/wiki/faq/freestore-mgmt#multidim-arrays

In a nutshell, select your matrix in one piece, 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 is highlighted in one fragment, you can also delete it in one fragment.

Or you can do something similar to what you are doing, but distribute for each row. Be sure to delete each row first, and then the matrix.

The related article also contains information about wrapping unpleasant pointer / array material in a class.

+4
source

An array of pointers may be unnecessary. You could just select a 1D array of 9 elements and do the math to convert 2D indices to 1D indices.

In addition to replacing delete[] operations, you should consider what happens when distribution fails. If the second distribution throws std::bad_alloc , your program leaks memory from the first allocation. A correctly written matrix class (as suggested by Fred Larson) will handle memory freeing for you.

+1
source

Each element in the matrix array is int [], in addition, the matrix itself is an array int * (int * []), given these rules, you should do

delete [] matrix [i] {i = 0,1,2}

and then delete [] to delete the matrix itself.

Hope this helps. Thanks

-1
source

Source: https://habr.com/ru/post/1286100/


All Articles