new[] / delete

A

alariq

can i do this without any harm (assuming that type MyType does not
allocate ANY memory in heap)

MyType* pmytype = new MyType[10];

// do some stuff

delete pmytype;

AFAIK, it will free memory allocated for 10 instances of MyType but
will not call destructors (which i do not need) and nothis bad will
happen. Moreover i saw such code when working with native types (such
as char/int/etc) in production code.
What does standard says in this case?
Thanks
 
A

Alf P. Steinbach

* alariq:
can i do this without any harm (assuming that type MyType does not
allocate ANY memory in heap)

MyType* pmytype = new MyType[10];

// do some stuff

delete pmytype;

AFAIK, it will free memory allocated for 10 instances of MyType but
will not call destructors (which i do not need) and nothis bad will
happen. Moreover i saw such code when working with native types (such
as char/int/etc) in production code.
What does standard says in this case?

It's Undefined Behavior.

In practice it will probably, *currently*, work regardless of compiler.

However, why invite later disaster?


Cheers & hth.,

- Alf
 
S

Saeed Amrollahi

can i do this without any harm  (assuming that type MyType does not
allocate ANY memory in heap)

MyType* pmytype = new MyType[10];

// do some stuff

delete pmytype;

AFAIK, it will free memory allocated for 10 instances of MyType but
will not call destructors (which i do not need) and nothis bad will
happen. Moreover i saw such code when working with native types (such
as char/int/etc) in production code.
What does standard says in this case?
Thanks

Hi

According to C++ Standard Document -- ISO-IEC_14882.2003, section
5.3.5, the
behavior is undefined. May be on some implementations, just the first
element of
array will be deleted.
In both cases:
delete object
delete [] array
the destructor called.
In that case, there is no difference between built-in data types and
user-defined data types.
Programmer should use new/new[] and delete/delete[] in regular manner.
See the following links:
http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.12
http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.13

Regards,
-- Saeed Amrollahi
 

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
473,982
Messages
2,570,186
Members
46,739
Latest member
Clint8040

Latest Threads

Top