Search code examples
c++dynamicstructurenew-operatorallocation

How do I over-allocate memory using new to allocate variables within a struct?


So I have a couple of structs...

struct myBaseStruct
{
};

struct myDerivedStruct : public myBaseStruct
{
    int a, b, c, d;
    unsigned char* ident;
};

myDerivedStruct* pNewStruct;

...and I want to dynamically allocate enough space so that I can 'memcpy' in some data, including a zero-terminated string. The size of the base struct is apparently '1' (I assume because it can't be zero) and the size of the derived is 20, which seems to make sense (5 x 4).

So, I have a data buffer which is a size of 29, the first 16 bytes being the ints and the remaining 13 being the string.

How can I allocate enough memory for pNewStruct so that there is enough for the string? Ideally, I just want to go:

  • allocate 29 bytes at pNewStruct;
  • memcpy from buffer into pNewStruct;

Thanks,


Solution

  • You can allocate any size you want with malloc:

    myDerivedStruct* pNewStruct = (myDerivedStruct*) malloc(
          sizeof(myDerivedStruct) + sizeof_extra data);
    

    You have a different problem though, in that myDerivedStruct::ident is a very ambigous construct. It is a pointer to a char (array), then the structs ends with the address where the char array starts? ident can point to anywhere and is very ambigous who owns the array ident points to. It seems to me that you expect the struct to end with the actual char array itself and the struct owns the extra array. Such structures usualy have a size member to keep track of teir own size so that API functions can properly manage them and copy them, and the extra data starts, by convention, after the structure ends. Or they end with a 0 length array char ident[0] although that creates problems with some compilers. For many reasons, there is no place for inheritance in such structs:

    struct myStruct 
    {
    size_t size;    
    int a, b, c, d;    
    char ident[0];
    };