delete[] on array of size 1

R

Roger Davis

I've been reading lately about the necessity of using

delete[] p;

instead of

delete p;

whenever p was allocated as an array, e.g.,

p= new int[20];

I assume this is true even when p is an array of one element, e.g.,

p= new int[1];

Can anyone verify this?

Has this distinction between 'delete[] p' and 'delete p' always
existed in C++? Somehow I missed this point and have been programming
using only 'delete p' for years, with no apparent ill effects. Have I
just been amazingly lucky?

Thanks.
 
K

Kevin Goodsell

Marcin Vorbrodt wrote:

Please do not top-post. Re-read section 5 of the FAQ for posting guidelines.

http://www.parashift.com/c++-faq-lite/

Message re-arranged.
Has this distinction between 'delete[] p' and 'delete p' always
existed in C++? Somehow I missed this point and have been programming
using only 'delete p' for years, with no apparent ill effects. Have I
just been amazingly lucky?
Yes.

No matter the array size, you always need to call delete[] on it.
If you dont, only the first element of the element will be deleted
(I think).

No, the behavior is undefined. Anything could happen, including the
program crashing, random file deletion, resource leaks, or the program
appearing to work as expected.

-Kevin
 
R

Ron Natalie

Marcin Vorbrodt said:
No matter the array size, you always need to call delete[] on it. If you
dont, only the first element of the element will be deleted (I think).
No, it's undefined behavior. Anything might happen.
 
R

Ron Natalie

Zhang Yan said:
there's probably no ill effects if you use int or POD types, but will couse
ill effects if you use
non-POD types.

Probably is a bad word. The standard makes it unconditionally undefined behavior.
You can't make assumptions about what might happen.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,141
Messages
2,570,817
Members
47,365
Latest member
BurtonMeec

Latest Threads

Top