tags:

views:

194

answers:

5

Possible Duplicate:
( POD )freeing memory : is delete[] equal to delete ?

char* pChar = new char[10];

delete pChar; // this should not work but it has same effect as 
              // delete[], WHY?
              // I know this is illegal, but why does it work?
+8  A: 

Because you got lucky. This is undefined behavior. One possibility for undefined behavior is that nothing bad seems to happen, even if something bad really did happen. You might not find out until later.

You can't count on being safe with primitive types. Read this (also linked by James Roth in a comment): http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.13

Fred Larson
+11  A: 

It may appear to have the same effect, but it does not. If your array type was an abstract data type (i.e. a class) then the destructors on the last nine elements would not have been called.

Amardeep
yes, I tried that, it only works with primitive types.
Gollum
Also, if the type of the array was of a non POD that redefined delete and delete[], the first one would be called instead of the second one, which may lead to even more surprising results. The same holds if the global delete and delete[] were redefined.
Matteo Italia
Or if the compiler itself handled single allocations and array allocations differently, as it's allowed to do. Then it wouldn't "work" even with primitive types. Undefined behaviour is undefined.
Mike Seymour
+5  A: 

It doesn't work. It simply appears to work. The code that exhibits undefined behavior might appear to be "working" at the first sight, just like a program ridden with bugs might appear to "work fine" on a poorly selected test suite.

AndreyT
@AndreyT I like your answer, the way you put it, thanks. :)
Gollum
+1  A: 

It's undefined behavior. And since "it works this time" falls into the category of "undefined", it can work on some platform, on some compiler. Still, it shouldn't be done. Have you tried deallocing an array of objects with destructors like that, and seeing if the destructors get called?

EDIT : According to your comments, you did...

fingerprint211b
A: 

In most versions of Microsoft Visual Studio this actually works correctly. However, there's no reason why this should be so, it's totally upto your platform.

The idea behind delete[] is that this is a special case in which size is not known at compile time, which the allocation framework might want to handle differently (and optimize the delete case).

Strictly speaking, delete pointerToBaseClass also doesn't have size known at compile time, but this is solved by virtual table, and compiler knows that the class is polymorphic at compile time.

If you mishandle delete[], it may also have problems with tools replacing the allocator (debuggers, boundscheckers of all kinds, etcetc) and custom allocators your users may use.

Pavel Radzivilovsky