1

I have below code which is crashing.

aClass *ptr_obj = new aClass[5];
delete ptr_obj;

I know, ptr_obj is to be deleted using delete[], but my question here is why it crashes when I use delete. I was thinking it will call destructor for first object instead of crash. Please help.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Srikanth
  • 517
  • 3
  • 10
  • 29

1 Answers1

5

Arrays allocated with new[] must be deleted with delete[], otherwise it's undefined behavior.

Change your code to

delete[] ptr_obj;
   // ^^

"but my question here is why it crashes when I use delete."

Because if you do otherwise, you are calling undefined behavior.

"I was thinking it will call destructor for first object instead of crash."

It doesn't.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • OP says "I know, ptr_obj is to be deleted using `delete[]`", and then asks "why does it crash when I use `delete`?". – barak manos Dec 08 '14 at 12:11
  • @barakmanos I've been extending on this. – πάντα ῥεῖ Dec 08 '14 at 12:11
  • I would try to provide a practical answer as well ("undefined behavior" is accurate according to the standard, but it doesn't tell you what practically happens). As far as we can tell, using `delete` here should merely cause a memory leak, not a runtime exception. We can guess that something goes wrong in the destructor (which, by the way, should yield the same crash when using `delete[]`). Since the destructor code is missing, you might want to "encourage" OP to add it to the question, and in addition, to describe the behavior when using `delete[]` (which I suspect be the same). – barak manos Dec 08 '14 at 12:14
  • 1
    @barakmanos _"As far as we can tell, using delete here should merely cause a memory leak, not a runtime exception."_ How can we tell this? – πάντα ῥεῖ Dec 08 '14 at 12:19
  • Because we would expect `delete` to take on the first element, and `delete[]` to take on all elements (starting from the first one). – barak manos Dec 08 '14 at 12:21
  • @barakmanos According to the standard, all _we can expect_ is UB. – πάντα ῥεῖ Dec 08 '14 at 12:22
  • OK, so we're back to square one (avoiding a practical answer). Most users here are OK with that, as can be seen in the up-votes for your answer. – barak manos Dec 08 '14 at 12:23