A common pattern in C programming involves a variable length structure such as:
typedef struct {
    int length;
    char data[1];
} MyBuffer;
where data isn't literally an array of [1].  Instead, its variable length is defined by length.
The structure is allocated like:
MyBuffer* pBuff = malloc(sizeof(MyBuffer) + 100);
I want to use the same pattern, but in C++ code, so using new/delete instead of malloc/free
Can this same pattern be used in C++ code? How?
EDIT Since several answers and comments are suggesting I switch to std::vector:
I am supplied with the structure definition MyBuffer from a 3rd party, C library.
In my C++ app, I need to allocate the buffer and call a function in the C library.
On "my side" of the boundary, I prefer to keep things C++, and allocate this structure the C++-way,
but I still need to pass it to a C-library that won't understand anything like a std::vector.
If you need to maintain compatibility with the existing C code you are using, then it works with C++, pretty much unchanged (just a need to cast the return from malloc()).
#include <stdlib.h>
typedef struct {
    int length;
    char data[1];
} MyBuffer;
void f() {
    MyBuffer* pBuff = (MyBuffer *)malloc(sizeof(MyBuffer) + 100);
}
This compiles without issue using g++.
If you are concerned about managing the memory allocated my malloc() then you could create a class to manage it and expose the MyBuffer pointer via a member method, for example:
std::shared_ptr<MyBuffer> buf((MyBuffer *)malloc(sizeof(MyBuffer) + 100), free);
Which is pretty cumbersome, I'll admit...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With