Search code examples
c++memoryplacement-new

Is it alright to reuse a deleted address allocation?


Let's say I have this code:

Obj*  objects[10];
char* buffers[10];
// ...
buffers[1] = new char[sizeof(Obj)];
objects[1] = new(&buffers[1]) Obj();
// ...
objects[1]->~Obj();
delete[] buffers[1];

Would it be alright to reuse buffers[1] after calling delete?

What I mean by reuse is to use that address space again as the allocated address.

I mean by using this code

objects[2] = new(&buffers[1]) A();

Solution

  • First of all: placement new expects a pointer, not a pointer to a pointer

    objects[1] = new(&buffers[1]) Obj(); // Nope
    objects[1] = new(buffers[1]) Obj();  // Yes
    

    That said, after you've deleted the memory pointed by buffers[1] you need to allocate new memory before using it to store another instance of an object.

    That is the purpose of new[] and delete[] in the first place: marking a chunk of memory as "no longer needed" or "in use".

    You can however of course reuse the pointer buffers[1] to point to a new memory location but doing this after the code you posted is invalid:

    objects[2] = new(buffers[1]) A();
    

    since you're trying to build an object on a deleted memory location. That is going to trigger undefined behavior.

    This is valid instead

    Obj*  objects[10];
    char* buffers[10];
    // ...
    buffers[1] = new char[sizeof(Obj)];
    objects[1] = new(buffers[1]) Obj();
    // ...
    objects[1]->~Obj();
    delete[] buffers[1];
    
    // Allocate something else and build an object there. Remember that
    // 'objects' is an array of pointers to Obj objects
    buffers[1] = new char[sizeof(Obj)];
    objects[1] = new(buffers[1]) Obj();
    // You might now destroy and deallocate