c / expert
Snippet
Flexible Array Member Allocation and Memory Layout Optimization
C99 introduced Flexible Array Members (FAMs), allowing a structure to end with an incomplete array type. This technique enables a single malloc call to allocate both the descriptor metadata and contiguous dynamically sized payload data. Performing single-block allocation maximizes cache locality and eliminates secondary pointer dereferencing overhead compared to using a separate heap pointer member.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <stdio.h>#include <stdlib.h>#include <string.h>typedef struct {size_t length;char payload[]; /* C99 Flexible Array Member */} DynamicBuffer;DynamicBuffer* create_buffer(const char *data) {size_t len = strlen(data);/* Allocate header and variable payload in a single contiguous memory block */DynamicBuffer *buf = malloc(sizeof(DynamicBuffer) + len + 1);if (!buf) return NULL;buf->length = len;memcpy(buf->payload, data, len + 1);return buf;}int main(void) {DynamicBuffer *buf = create_buffer("Expert C Memory Layout");if (buf) {printf("Len: %zu, Content: %s\n", buf->length, buf->payload);free(buf);}return 0;}
Breakdown
1
char payload[]; /* C99 Flexible Array Member */
Declares an unsized trailing array inside the struct, contributing zero bytes to sizeof(DynamicBuffer).
2
DynamicBuffer *buf = malloc(sizeof(DynamicBuffer) + len + 1);
Allocates a single contiguous memory region housing both struct header metadata and the string payload.