capypad
0 day streak
c / expert
Snippet

Flexible Array Members (C99)

A flexible array member is an unsized array declaration at the end of a struct. It allows for a single contiguous memory allocation for both the metadata (header) and the payload (data). This avoids double-pointer indirection, simplifies memory management, and significantly improves cache locality compared to a pointer to a separate heap allocation.

snippet.c
c
1
2
3
4
5
6
7
8
struct Packet {
int header_id;
size_t length;
unsigned char data[]; // Flexible array member
};
 
struct Packet *p = malloc(sizeof(struct Packet) + 1024);
p->length = 1024;
Breakdown
1
unsigned char data[];
Declares an array with no fixed size; it must be the last member of the struct.
2
malloc(sizeof(struct Packet) + 1024)
Allocates space for the struct members plus additional space for the 'data' array.