Is there any effective difference between these two styles of allocating memory?
1.
typedef struct {
uint8_t *buffer;
} Container;
Container* init() {
Container* container = calloc(sizeof(Container), 1);
container->buffer = calloc(4, 1);
return container;
}
2.
typedef struct {
uint8_t buffer[4];
} Container;
Container* init() {
Container* container = calloc(sizeof(Container), 1);
return container;
}
As far as I understand, the whole Container
struct will be heap allocated and buffer
will point to the same. Is this correct?
There is a difference.
I'll try to illustrate the sample.
As others pointed out:
As pointed out in comments: In case if buffer is a last element in a structure (like in the example provided) it is possible to allocate any length for the buffer.
For example
int extra_bytes_needed = ...;
Container* container = calloc(sizeof(Container) + extra_bytes_needed, 1);
On the left side of image - your first case.
On the right side of image- your second case.