Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common C pattern, but expressed in C++?

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.

like image 328
abelenky Avatar asked Dec 01 '22 20:12

abelenky


1 Answers

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...

like image 61
trojanfoe Avatar answered Dec 03 '22 10:12

trojanfoe