0

In the following program new reuses a memory allocated by malloc. But how to free the memory then? by free or by delete? how to call the destructor?

#include <iostream>

struct A
{
    A()  {}
    ~A() {}
};
int main()
{
    void* p = malloc(sizeof(A));
    A* pa = new (p) A();

    // codes...


    delete pa;
    // pa ->~A();
    // free(p);
}

Is it safe to reuse malloc memory by new? And how to free the memory?

Minimus Heximus
  • 2,683
  • 3
  • 25
  • 50

1 Answers1

1

new (p) A() is placement new that doesn't allocate memory and only calls the constructor.

Calling regular delete on that pointer returned by placement new is undefined behaviour.

To deallocate correctly here you need to call the destructor and then free the memory:

pa->~A(); // or, in C++17 std::destroy_at(pa);
free(pa);
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271