Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does delete[] free correctly in this code?

Consider the following way of working with a dynamically allocated two-dimensional array (for some reason, this way does not appear among the replies here):

const int nRows = 2, nCols = 3;
int (*arr)[nCols] = (int(*)[nCols])(new int[nRows * nCols]);
arr[1][1] = 2;
std::cout << arr[1][1] << endl;
delete[] arr;

Does delete[] in the last line free the memory correctly in this case?

like image 570
AlwaysLearning Avatar asked Jun 17 '26 17:06

AlwaysLearning


1 Answers

This is undefined behaviour; the type of the argument to delete must have the same type as the result of the corresponding new.

You could improve the code with:

int (*arr)[nCols] = new int[nRows][nCols];

(or even auto *arr = ...) in which case the same delete expression would be correct. Having to use a cast is generally a sign you've taken a mis-step.

like image 179
M.M Avatar answered Jun 20 '26 08:06

M.M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!