Search code examples
c++memory-managementnew-operatorplacement-new

Can I call delete on the pointer which is allocated with the placement new?


Can we call delete on the pointer which is allocated with the placement new? If no then why? Please explain in details.

I know that there is no placement delete. But I wonder why just delete opetator can not delete the memory without caring how that memory on which the pointer points is allocated?

delete is doing two things:

  1. Calls destrucor
  2. Frees memory

And I see no reaason for delete not to be able to call either of these two operations on the object which was created by placement new. Any idea about reasons?


Solution

  • EDIT1: I know that there is no placement delete. But I wonder why just delete opetator can not delete the memory without caring how that memory on which the pointer points is allocated?

    Because each flavour of memory allocation uses some implementation specific tracking of the memory (usually a header block that precedes the user address) and this make the allocation/deallocation to work only when paired up correctly:

    • new must pair with delete
    • new[] must pair with delete[] (most implementations though forgive mixing the newand new[])
    • malloc and frieds must pair with free
    • CoTaskMemAlloc pairs with CoTaskMemFree
    • alloca pairs with nothing (stack unwinding takes care of it)
    • MyCustomAllocator pairs with MyCustomFree

    Attempting to call the wrong deallocator will result in unpredictable behavior( most likely seg fault now or later). Therefore calling delete on memory allocated by anything else other than new will result in bad things.

    Furthermore the placement new may be called on any address, may not even be an allocated address. It can be called on an address located in the middle of some larger object, it may be called on a memory mapped region, it may be called on a raw virtual committed region, anything goes. delete woul attempt, in all these cases, to do what its implementation tell him to do: subtract the header size, interpret it as a new header, link it back into the heap. Kaboom.

    The one that know how to release the memory of a placement new address is you, since you know exactly how was that memory allocated. delete will only do what it knows, and it may not be the right thing.