Flexible Array Members in C
A flexible array member (C99) ends a struct with an unsized array — struct Buf { size_t len; char data[]; }; — letting one allocation hold header plus payload contiguously: malloc(sizeof(struct Buf) + n). The struct itself contributes no storage for the member (sizeof ignores it), and the trailing array indexes exactly like a normal one.
This replaces the old struct-hack (char data[1] with over-allocation) with defined behavior, powering network packets, variable records, and string builders. Rules: last member only, no arrays of such structs, and always allocate header-plus-payload together.
Unsized trailing array
char data[]; as the final member claims no storage itself — the struct is a header awaiting its payload.
Allocate together
malloc(sizeof(struct Buf) + n) reserves header plus n payload bytes in one block — one allocation, one free.
Index normally
b->data[i] works like any array within the allocated span — bounds are your documented contract.
Replaces the struct hack
Old char data[1] over-allocation was undefined behavior that happened to work; flexible members are the defined version.
#include <stdio.h>#include <stdlib.h>#include <string.h> struct Msg { int id; char text[];}; int main(void) { struct Msg *m = malloc(sizeof *m + 6); if (!m) return 1; m->id = 7; memcpy(m->text, "hello", 6); printf("%d %s\n", m->id, m->text); free(m); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.