-1

I know that to create array in C++ use new [] and delete this array use delete []

I wonder if I create a object and delete this with delete []

Test * a = new Test;
delete [] a;

Well... it works... but is it safe? should I use delete without bracket?

zno
  • 33
  • 3
  • When you say it "works", what does that mean? What behavior do you think constitutes working? – David Schwartz May 01 '14 at 23:20
  • Hmm, how to find the questions this is a dupe of.... – Ben Voigt May 01 '14 at 23:20
  • Somebody use [the question qeadz](http://stackoverflow.com/questions/703691/how-does-delete-know-its-an-array-c) found (see answer [comments](http://stackoverflow.com/questions/23418295/is-this-possible-that-new-without-bracket-but-delete-with-bracket-in-c#comment35886954_23418318)) as dupe target as well, so both get shown. – Ben Voigt May 01 '14 at 23:24
  • If Richard's answer covers it, you should select it as your chosen answer *nudge nudge* – qeadz May 01 '14 at 23:49

2 Answers2

4

No, it's not ok. Behaviour will be at best undefined.

edit:

Info link added by popular request: http://web.archive.org/web/20080703153358/http://taossa.com/index.php/2007/01/03/attacking-delete-and-delete-in-c

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
  • 2
    Duplicate of http://stackoverflow.com/questions/703691/how-does-delete-know-its-an-array-c – qeadz May 01 '14 at 23:21
  • @qeadz: Great article linked from the comments there, too. – Ben Voigt May 01 '14 at 23:24
  • @Richard sorry I replied in the wrong place. this was meant to be to the question :/ anyway Ben is right that the article is really good. Perhaps add it to your answer if you care since it's a great explanation. http://web.archive.org/web/20080703153358/http://taossa.com/index.php/2007/01/03/attacking-delete-and-delete-in-c – qeadz May 01 '14 at 23:33
  • info link added as requested. – Richard Hodges May 01 '14 at 23:48
2

It's undefined behaiviour and best avoided.
IIRC MSVC handles (or at least used to handle ) new and array new identically which is (or was) a delightful source of migration headaches ;-)

thus spake a.k.
  • 1,607
  • 12
  • 12
  • They can be handled the same for primitive types, but never for types with a non-trivial destructor. – Ben Voigt May 01 '14 at 23:25
  • @BenVoigt: I seem to recall MSVC managing it for non-trivial UDTs. I suspect it did so by having array delete complexity for non-array delete (i.e. implementing them both the same way). I've no idea whether it's still that bad. – thus spake a.k. May 01 '14 at 23:31
  • It's not allowed for non-array `new` to work like array `new` (storing the count). non-array `new` has zero storage overhead (in terms of the size of the block requested from `::operator new`), mandated by the Standard. – Ben Voigt May 01 '14 at 23:34
  • @BenVoigt: MSVC played pretty fast and loose with what was allowed ;-) – thus spake a.k. May 01 '14 at 23:46