By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,570 Members | 1,251 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,570 IT Pros & Developers. It's quick & easy.

delete op question. do I need to cast?

P: n/a
Hello

Consider this:

// allocate a buffer, and cast to MYSTRUCT
MYSTRUCT *p = (MYSTRUCT *) new char[sizeof(MYSTRUCT) + 100];

// free the buffer

// 1. can I free directly as:
delete [] p;

// 2. or as:
delete p;

// 3. or better, to cast to char* and delete, as:
delete [] (char *)p;

Which is correct (if any)?

The struct doesn't have any dtor or ctor() it is just a plain C struct.

--
Elias
Jul 22 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a

"lallous" <la*****@lgwm.org> wrote in message
news:2r*************@uni-berlin.de...
Hello

Consider this:

// allocate a buffer, and cast to MYSTRUCT
MYSTRUCT *p = (MYSTRUCT *) new char[sizeof(MYSTRUCT) + 100];

// free the buffer

// 1. can I free directly as:
delete [] p;

// 2. or as:
delete p;

// 3. or better, to cast to char* and delete, as:
delete [] (char *)p;

Which is correct (if any)?

3 is correct.
The struct doesn't have any dtor or ctor() it is just a plain C struct.


That makes no difference as far as correctness goes.

john
Jul 22 '05 #2

P: n/a


I wouldn't use "new" here. Use "malloc" and the rest...
-JKop
Jul 22 '05 #3

P: n/a

"lallous" <la*****@lgwm.org> wrote in message
news:2r*************@uni-berlin.de...
Hello

Consider this:

// allocate a buffer, and cast to MYSTRUCT
MYSTRUCT *p = (MYSTRUCT *) new char[sizeof(MYSTRUCT) + 100];

// free the buffer

// 1. can I free directly as:
delete [] p;

// 2. or as:
delete p;

// 3. or better, to cast to char* and delete, as:
delete [] (char *)p;

Which is correct (if any)?


Of course
delete [] (char *)p;
is correct.
Use typecasts only when necessary. They bypass the type-checking rules of
the language.
Also if you have some dlls take care to delete from the same module where
you allocated the data with new.

Timothy Madden
Romania
-----------------------------------------------
And I don't wanna miss a thing
Jul 22 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.