Free memory allocated from placement

Consider the following code:

#include "iostream" #include "conio.h" using namespace std; class sample { private: int i; public: sample(int ii=0) : i(ii){ cout<<"Constructing Object"<<endl; } ~sample() { cout<<"Destructing Object"<<endl; } void* operator new(size_t nSize, void* loc){ cout <<"Inside new"<<endl; cout <<loc<<endl; return loc; } void operator delete(void* ptr){ cout <<"Inside delete"<<endl; free(ptr); } }; int main() { int intArr[2]; sample* samplePtr = new(intArr) sample(5); cout <<samplePtr<<endl; delete samplePtr; // samplePtr->sample::~sample(); getch(); } 

Output:

 Inside New 0x22ff38 Constructing Object 0x22ff38 Destructing Object Inside Delete 

Here I am dynamically requesting memory that is already allocated on the stack. I read that I need to call the destructor explicitly as soon as I finish. But when I try to call delete on the memory allocated on the stack, I get a call to the destructor. Does this mean that the memory on the stack is freed up after the destructor is called?

If I dynamically request memory allocated earlier on the heap, then I need to call delete, but is it really possible to delete free memory on the stack?

+2
source share
3 answers

A normal new statement does two things:

  • Calls a dynamic memory manager to retrieve a piece of memory
  • Call constructor

The normal delete operator does the reverse

  • Destructor call
  • Invokes a dynamic memory manager to free memory

Placing a new one only takes one step:

  • Call constructor

Thus, “deleting a placement” should only take one step:

  • Destructor call

You should not cause normal deletion after posting a new one, as you did. (The reason is that the dynamic memory manager must delete a block that it did not allocate, which led to undefined behavior)

This line is incorrect:

 delete samplePtr; // WRONG 

You need to do a "delete placement", which is just a raw descriptor call:

 samplePtr->~sample(); // CORRECT 
+14
source

What you do (free memory with free that was not allocated by malloc ) causes undefined behavior - anything can happen. Same thing with delete with a pointer that was not obtained via new . Same thing with delete with a pointer retrieved from malloc or vice versa.

Just because it seems to be “working,” does not mean that it is correct. You should not be free to store stack memory. You are correct that you need to call the destructor directly in this case.

+1
source

This is why posting a new one can be bad (in fact, you should avoid it where possible, in this case just the stack allocates an object), you should not delete memory (because it was never created new in the first place, rather, you need make samplePtr->~sample();

0
source

Source: https://habr.com/ru/post/1494972/


All Articles