Search code examples
c++memoryshared-ptr

Zero sized array in struct managed by shared pointer


Consider the following structure:

struct S
{
    int a;
    int b;
    double arr[0];
} __attribute__((packed));

As you can see, this structure is packed and has Zero sized array at the end. I'd like to send this as binary data over the network (assume I took care of endianity).

In C/C++ I could just use malloc to allocate as much space as I want and use free later.

I'd like this memory to be handled by std::shared_ptr.

Is there a straight forward way of doing so without special hacks?


Solution

  • I'd like this memory to be handled by std::shared_ptr.

    Is there a straight forward way of doing so without special hacks?

    Sure, there is:

    shared_ptr<S> make_buffer(size_t s)
    {
        auto buffer = malloc(s);                    // allocate as usual
        auto release = [](void* p) { free(p); };    // a deleter
        shared_ptr<void> sptr(buffer, release);     // make it shared
        return { sptr, new(buffer) S };             // an aliased pointer
    }
    

    This works with any objects that are placed in a malloced buffer, not just when there are zero-sized arrays, provided that the destructor is trivial (performs no action) because it is never called.

    The usual caveats about zero-sized arrays and packed structures still apply as well, of course.