www.digitalmars.com Home | Search | C & C++ | D | DMDScript | News Groups | index | prev | next
Archives

D Programming
D
D.gnu
digitalmars.D
digitalmars.D.bugs
digitalmars.D.dtl
digitalmars.D.dwt
digitalmars.D.announce
digitalmars.D.learn
digitalmars.D.debugger

C/C++ Programming
c++
c++.announce
c++.atl
c++.beta
c++.chat
c++.command-line
c++.dos
c++.dos.16-bits
c++.dos.32-bits
c++.idde
c++.mfc
c++.rtl
c++.stl
c++.stl.hp
c++.stl.port
c++.stl.sgi
c++.stlsoft
c++.windows
c++.windows.16-bits
c++.windows.32-bits
c++.wxwindows

digitalmars.empire
digitalmars.DMDScript

c++ - placement new bug

↑ ↓ ← "Laurentiu Pancescu" <user domain.invalid> writes:
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
→ "Laurentiu Pancescu" <user domain.invalid> writes:
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 here

   return 0;
 }

Mar 18 2002
→ "Walter" <walter digitalmars.com> writes:
"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 as

 int, and that if the program doesn't return a value from main, a "0" must

 silently returned by the compiler (in the special case of main only!).

 gives 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