1

Consider:

int *p = new int[10];

The linked reply states:

NOTE: One can free the memory even by delete p;, but it will free only the first element memory.

This sounds like delete p is OK. Is this correct? I would expect that delete p should result in undefined behavior...

AlwaysLearning
  • 7,257
  • 4
  • 33
  • 68
  • A memory leak is not undefined behavior. – Beta Jan 02 '20 at 18:28
  • 3
    Does this answer your question? [Should new/new\[\] match delete/delete\[\]?](https://stackoverflow.com/questions/4480722/should-new-new-match-delete-delete) – Richard Critten Jan 02 '20 at 18:30
  • The dynamic array is allocated as one block of contiguous memory. Deleting one cell in the block is undefined behavior and a pain to maintain the memory allocation (i.e. how does one mark a memory cell of an array as deleted but keep all the others?). – Thomas Matthews Jan 02 '20 at 18:31
  • C++11 Paragraph 5.3/2 : "[...] In the first alternative (delete object), the value of the operand of delete may be a null pointer value, a pointer to a non-array object created by a previous new-expression, or a pointer to a subobject ([intro.object]) representing a base class of such an object (Clause [class.derived]). If not, the behavior is undefined. [...]" – Aykhan Hagverdili Jan 02 '20 at 18:35
  • 1
    It is UB using version of `delete` that doesn't match `new`. – Maestro Jan 02 '20 at 18:55

1 Answers1

3

It's not OK, and the statement is not correct.

The behaviour of using delete on a pointer from new[] (or indeed, any pointer not from new) is undefined. delete[] should be used instead.

eerorika
  • 232,697
  • 12
  • 197
  • 326