| View previous topic :: View next topic |
| Author |
Message |
lallous Guest
|
Posted: Mon Sep 27, 2004 9:32 am Post subject: delete op question. do I need to cast? |
|
|
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
|
|
| Back to top |
|
 |
JKop Guest
|
Posted: Mon Sep 27, 2004 10:01 am Post subject: Re: delete op question. do I need to cast? |
|
|
I wouldn't use "new" here. Use "malloc" and the rest...
-JKop
|
|
| Back to top |
|
 |
John Harrison Guest
|
Posted: Mon Sep 27, 2004 10:01 am Post subject: Re: delete op question. do I need to cast? |
|
|
"lallous" <lallous (AT) lgwm (DOT) org> wrote
| Quote: | 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.
| Quote: | 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
|
|
| Back to top |
|
 |
Timothy Madden Guest
|
Posted: Mon Sep 27, 2004 10:04 am Post subject: Re: delete op question. do I need to cast? |
|
|
"lallous" <lallous (AT) lgwm (DOT) org> wrote
| Quote: | 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
|
|
| Back to top |
|
 |
|