Malloc of arrays and structs within a struct

system picture system · Mar 29, 2011 · Viewed 27.2k times · Source

How does one malloc a struct which is inside another struct?

I would also like to malloc an array of items inside a struct and then realloc this array when needed, how is this done correctly?

Could you please give an example of declaring a struct and then the above.

Im a little unsure of the order of things.

Would the array within a struct be freed and then the struct itself, must the struct be malloced when it is created and then its fields be malloced/declared etc?

Answer

Sylvain Defresne picture Sylvain Defresne · Mar 29, 2011

A struct included inside another struct is contained by copy, so you would not have to separately malloc it. If the struct contains a pointer to another struct, then you can consider allocating memory for it dynamically.

struct Point2d
{
    float x;
    float y;
};

struct Rect
{
    struct Point2D a;
    struct Point2D b;
};

struct LinkedListNode
{
    struct LinkedListNode* next;
    int value;
};

In struct Rect, the struct Point2D element are inserted into struct Rect and you don't have to dynamically allocate memory for them. On the contrary in the struct LinkedListNode the next element is referenced by a pointer and the memory must be dynamically allocated.

The two version are both useful, depending on the situation. There is no correct way to manage memory, it'll depend on your usage.

This same situation occurs in the case of an array. If your array is statically sized, then it can be directly included in the struct. However, if the size can vary, you must store a pointer within the struct.

struct Header
{
    char magic[4];
    unsigned int width;
    unsigned int height;
};

struct Buffer
{
    char* data;
    unsigned int size;
    unsigned int capacity;
};

struct Buffer* buffer_init()
{
    struct Buffer* buffer = (struct Buffer*)malloc(sizeof(struct Buffer));
    buffer->data = 0;
    buffer->size = 0;
    buffer->capacity = 0;
}

void buffer_grow(struct Buffer* buffer, size_t capacity)
{
    if (capacity > buffer->capacity)
    {
        buffer->data = realloc(buffer->data, capacity);
        buffer->capacity = capacity;
    }
}

void buffer_append(struct Buffer* buffer, const char* data, unsigned int dataLen)
{
    if (dataLen + buffer->size > buffer->capacity)
        buffer_grow(MAX(dataLen + buffer->size, buffer->capacity * 2));

    memcpy(buffer->data + buffer->size, data, dataLen);
    buffer->size += dataLen;
}

The realloc function only does a shallow copy, that is pointer value is copied, but not the pointed object. One more time, how you deal with it will depend on your application.