0

Code snippet:

#include <new>
char buffer[512];

int main()
{
   double *pd;
   pd = new (buffer) double[5];
   delete [] pd;
   return 0;
}

This only hangs when using the placement new form of the new operator.

I'm using the following tools and options:

> cl -EHsc foobar.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 18.00.21005
Microsoft (R) Incremental Linker Version 12.00.21005.1
user2939875
  • 309
  • 1
  • 7
  • Sort of a dupe of http://stackoverflow.com/questions/4418220/legality-of-using-operator-delete-on-a-pointer-obtained-from-placement-new – Ben Voigt Nov 03 '13 at 01:05

3 Answers3

0
pd = new (buffer) double[5];

What you are doing there is reusing the memory that buffer occupied to create an array of double. So now you are deleting a memory that you didn't not allocate with new.

Caesar
  • 9,483
  • 8
  • 40
  • 66
0

Don't do that. The program didn't allocate the memory with operator new or operator new[], so shouldn't delete it.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
0

You did not allocate that memory, so you should not try to free it (with delete []).

In general, you would run the destructors:

for( i = 0; i < 5; i++ ) {
    T* p = pd + i;
    p->~T();
}

But for double that isn't necessary.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720