0 day streak
c / expert
Snippet

Flexible Array Members (FAMs)

Flexible Array Members (introduced in C99) allow a structure to end with an unsized array. This technique enables a single heap allocation to contain both the metadata header and the variable-length payload, improving cache locality and reducing allocation overhead compared to storing a separate pointer.

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
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
struct DynamicBuffer {
size_t size;
uint8_t data[]; // Flexible array member
};
int main() {
size_t n = 1024;
// Allocate header + n bytes for the array
struct DynamicBuffer *buf = malloc(sizeof(struct DynamicBuffer) + n);
if (!buf) return 1;
buf->size = n;
for (size_t i = 0; i < n; i++) buf->data[i] = (uint8_t)(i % 256);
printf("Size: %zu, First element: %u\n", buf->size, buf->data[0]);
free(buf);
return 0;
}
Breakdown
1
uint8_t data[];
The flexible array member must be the last element of the struct and has no specified size.
2
malloc(sizeof(struct DynamicBuffer) + n);
Memory is allocated for the base struct size plus the desired number of array elements.