What is a flexible array member?
Short answer: A flexible array member is an array with no size declared as the last member of a struct (C99). The struct describes a header followed by a variable amount of data, allocated in one block: malloc(sizeof(struct packet) + n). sizeof the struct does not include the array.
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
struct packet {
uint16_t len;
uint8_t type;
uint8_t data[]; /* flexible array member: must be last */
};
struct packet *packet_new(uint8_t type, const uint8_t *payload, uint16_t n)
{
struct packet *p = malloc(sizeof *p + n); /* header + n bytes, one allocation */
if (p == NULL) return NULL;
p->len = n;
p->type = type;
memcpy(p->data, payload, n);
return p; /* one free(p) releases everything */
}
Why use it
- One allocation and one
freeinstead of a header plus a separately allocated buffer. - The data is contiguous with the header (good for cache and for sending the whole thing with one DMA or
writecall).
Rules
- It must be the last member, and the struct must have at least one other member.
- A struct with a flexible array member cannot be an element of an array or a member of another struct (GCC allows the latter as an extension).
sizeof(struct packet)may include padding beforedata; usingoffsetof(struct packet, data) + ngives the minimum size.- Assigning or copying such structs by value copies only the header.
Older tricks you will see in legacy code: uint8_t data[1]; (the "struct hack": accessing beyond index 0 is technically undefined) and uint8_t data[0]; (a GNU extension). Modern compilers with -fstrict-flex-arrays and bounds checking treat these differently, so convert them to []. The Linux kernel completed this conversion and uses __counted_by(len) annotations so the compiler can bounds-check the array.
Embedded note: with static allocation, you can use the same type over a fixed buffer: static uint8_t storage[sizeof(struct packet) + 64] and a pointer to it, keeping the alignment of the struct in mind.