'reinterpret<char**> from new char[]

So I saw this piece of code that's confusing me:

class DynamicBuffer
{
    private:
    
        char* _buf = nullptr; 
   
    public:
        void Resize(size_t size)
        {
            char* resizeBuf = new char[size];
            char **ptr = reinterpret_cast<char**>(resizeBuf);
            *ptr = _buf;
            _buf = resizeBuf;
        }
}

I'm hung up on:

char **ptr = reinterpret_cast<char**>(resizeBuf);
*ptr = _buf;

Am I right in thinking the author was trying to make the first sizeof(char) bytes to point the older buffer? How is this not undefined behavior?

Why not just do this:

char** resizeBuf = new char*[size];
c++


Solution 1:[1]

This seems like a roundabout version of basically writing:

void Resize(size_t size)
{
    assert(size >= sizeof(char*));
    char* resizeBuf = new char[size];
    memcpy((void*)resizeBuf, (void*)&_buf, sizeof(_buf));
    _buf = resizeBuf;
}

Or using placement new to do essentially the same thing.

void Resize(size_t size)
{
    assert(size >= sizeof(char*));
    char* resizeBuf = new char[size];
    char** firstPointer = new(resizeBuf) char*;
    *firstPointer = _buf;
    _buf = resizeBuf;
}

I think the memcpy version happens to be well-defined because the default alignment for memory allocated with new __STDCPP_DEFAULT_NEW_ALIGNMENT__ should accomodate pointers.

Memcpy is also allowed to implicitly create new objects, which just a regular assignment is not allowed to do without the prior placement new.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1