c++ - placement new bug
- Laurentiu Pancescu (24/24) Mar 18 2002 I think that DMC's delete tries to free the memory which is not dynamica...
- Laurentiu Pancescu (11/21) Mar 18 2002 Errr... my mistake, sorry! Normally, one should call pa->~A(); what I
- Walter (6/11) Mar 18 2002 returning
I think that DMC's delete tries to free the memory which is not dynamically allocated, in case of using placement new. The following program crashes (-mn) or terminates with a "heap corruption" message (-mx). This is true also for placement new[], the sample code is almost the same, so I won't provide it here. The destructors should be executed, but the memory shouldn't be freed, because it wasn't allocated by new (the object was contructed directly at the user supplied address). // placement new demo (sc -mn -A) #include <new.h> class A {} int main() { static char buffer[1024]; A *pa = new (static_cast<A *>(buffer)) A; delete pa; // it crashes here return 0; } An extra note: ISO-C++ standard says that main must be declared as returning int, and that if the program doesn't return a value from main, a "0" must be silently returned by the compiler (in the special case of main only!). DMC gives a warning in normal mode, and an error in ANSI mode, if the "return 0;" line is missing. Regards, Laurentiu
Mar 18 2002
Errr... my mistake, sorry! Normally, one should call pa->~A(); what I wrongly thought is that this call is a mere method call, and, if A is derived from B, B's destructor doesn't get called. I was confused about gcc and BCC supporting calls to delete with pointers to objects obtained via placement new. I guess this is just an extension of the standard (I don't have a copy of it). Sorry about this! Laurentiu "Laurentiu Pancescu" <user domain.invalid> schrieb im Newsbeitrag news:a75lrs$2deg$1 digitaldaemon.com...// placement new demo (sc -mn -A) #include <new.h> class A {} int main() { static char buffer[1024]; A *pa = new (static_cast<A *>(buffer)) A; delete pa; // it crashes herepa -> ~A(); // this is the correct way, DMC handles it correctlyreturn 0; }
Mar 18 2002
"Laurentiu Pancescu" <user domain.invalid> wrote in message news:a75lrs$2deg$1 digitaldaemon.com...An extra note: ISO-C++ standard says that main must be declared asreturningint, and that if the program doesn't return a value from main, a "0" mustbesilently returned by the compiler (in the special case of main only!).DMCgives a warning in normal mode, and an error in ANSI mode, if the "return 0;" line is missing.I'll fix that one, too. -Walter
Mar 18 2002