0

Possible Duplicates:
Why is there a special new and delete for arrays?
( POD )freeing memory : is delete[] equal to delete ?

What's the result if I use delete p instead of delete [] p for an array? I met two answers for this problem.

1 only the first element will be freed.

2 there comes to a catastrophic end.

My question is, how can this two happen? Why there would be a disaster if only the first element is freed? Can anybody offer me an example?

Community
  • 1
  • 1
skydoor
  • 25,218
  • 52
  • 147
  • 201
  • 3
    It is undefined behaviour. It has also been asked here a zillion times before. See http://stackoverflow.com/questions/659270/why-is-there-a-special-new-and-delete-for-arrays among many, many others. –  Dec 16 '09 at 20:27

3 Answers3

5

You will get undefined behavior.

Kirill V. Lyadvinsky
  • 97,037
  • 24
  • 136
  • 212
4

It is undefined behavior.

What this means is that the standard gurantees to the writers of the memory management library that certain pre-conditions exist (In this case that arrays will be deleted with delete []).

If you break these pre-conditions then the memory management library could fail in some way. How it fails will depend on how the library is implemented. But since C++ is designed for speed the result is probably not going to be nice. So usually this means that the internal memory management data structures are corrupted in some way. This will probably lead to some other part of your program sigfaulting.

If you build in debug mode (on some compilers) they will use a special version of the memory management library that is designed to be more robust. Thus in these situations you may not crash but the extra checks have been explicitly added to the library and as a result is slower. But you still can not gurantee correct behavior.

Martin York
  • 257,169
  • 86
  • 333
  • 562
1

If only the first element is freed, you've leaked the rest of the array.

After several iterations of this, you run out of memory.

On the other hand, if it's undefined behaviour, the "catastrophic end" could instead be due to instantaneous death as winged demons spurt from your nasal cavities.

Anon.
  • 58,739
  • 8
  • 81
  • 86