Search code examples
cpointersmemorystructallocation

Difference between memory allocations of struct member (pointer vs. array) in C


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?


Solution

  • There is a difference.

    I'll try to illustrate the sample.

    As others pointed out:

    1. First example is harder to manage, but you can change size of the buffer any time.
    2. Second example is easier to manage (you don't have to care about freeing buffer separately), but you can only have fixed size of buffer.

    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.

    Left is first case, Right is second case.