c / expert
Snippet
Dynamic Header Structures using C99 Flexible Array Members
Explores the C99 flexible array member construct (payload[]), which enables single-allocation dynamic struct sizing where structural header metadata and trailing payload bytes reside contiguously in memory.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>#include <stdlib.h>#include <stdint.h>typedef struct {uint32_t length;uint32_t capacity;uint8_t payload[];} DynamicPacket;DynamicPacket* create_packet(uint32_t cap) {DynamicPacket* pkt = malloc(sizeof(DynamicPacket) + cap * sizeof(uint8_t));if (!pkt) return NULL;pkt->length = 0;pkt->capacity = cap;return pkt;}
Breakdown
1
uint8_t payload[];
Declares an unsized flexible array member at the end of the struct taking zero offset size by default.
2
sizeof(DynamicPacket) + cap * sizeof(uint8_t)
Calculates memory allocation size combining the fixed header size with the dynamic trailing payload buffer.
3
if (!pkt) return NULL;
Performs mandatory allocation safety checking before dereferencing struct pointer members.