3

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?

AlwaysLearning
  • 7,257
  • 4
  • 33
  • 68
  • 4
    Wherever you got "this way", it's wrong. The first sign it's broken is that cast, Ultimately you're not type-proper in freeing what you allocated. – WhozCraig Jan 08 '20 at 09:11

1 Answers1

7

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.

M.M
  • 138,810
  • 21
  • 208
  • 365
  • I believe `arr[1][1] = 2;` also violates strict aliasing in OP's code. – HolyBlackCat Jan 08 '20 at 09:11
  • @HolyBlackCat IMO it doesn't although that might be a topic for another question. Also it could be argued (quite well) that the result of the cast is not well-defined – M.M Jan 08 '20 at 09:14