Home >Backend Development >C++ >How to Properly Deallocate Memory Allocated with Placement New in C ?
placement new and delete Conundrum
In C , when allocating memory with the placement new operator, a dilemma arises regarding the appropriate method for deallocating that memory. Let's explore two potential solutions:
Solution 1:
<code class="c++">const char* charString = "Hello, World"; void *mem = ::operator new(sizeof(Buffer) + strlen(charString) + 1); Buffer* buf = new(mem) Buffer(strlen(charString)); delete (char*)buf;</code>
This solution attempts to delete the allocated memory as a character pointer. However, this approach is incorrect because it does not properly handle the object's destructor or deallocate the raw memory.
Solution 2:
<code class="c++">const char* charString = "Hello, World"; void *mem = ::operator new(sizeof(Buffer) + strlen(charString) + 1); Buffer* buf = new(mem) Buffer(strlen(charString)); delete buf;</code>
This solution also attempts to delete the allocated memory, but directly calls the delete operator on the Buffer* pointer. This would work if the memory was allocated using the regular new operator. However, since placement new was used, this approach is incorrect as well.
Correct Solution:
The correct method for freeing the allocated memory is:
<code class="c++">buf->~Buffer(); ::operator delete(mem);</code>
This solution explicitly calls the destructor for the Buffer object (buf->~Buffer()) and then deallocates the raw memory using the operator delete function (::operator delete(mem)).
The critical distinction here is that when using placement new, the operator delete function must be directly called to free the raw memory. Attempting to delete the pointer obtained from the placement new operator will not properly invoke the destructor or deallocate the memory entirely.
The above is the detailed content of How to Properly Deallocate Memory Allocated with Placement New in C ?. For more information, please follow other related articles on the PHP Chinese website!