c / expert
Snippet
Dynamic Storage Allocation using C99 Flexible Array Members
Flexible array members allow a structure to end with an unsized array declaration. Allocating memory for sizeof(struct) plus variable payload size yields a single contiguous block, reducing allocation overhead and improving cache locality compared to storing separate pointers.
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>struct Packet {size_t length;unsigned char payload[];};struct Packet *create_packet(const unsigned char *data, size_t len) {struct Packet *p = malloc(sizeof(*p) + len);if (!p) return NULL;p->length = len;for (size_t i = 0; i < len; i++) {p->payload[i] = data[i];}return p;}
Breakdown
1
struct Packet { size_t length; unsigned char payload[]; };
Defines a structure with an unsized array member at the end as payload storage.
2
struct Packet *p = malloc(sizeof(*p) + len);
Allocates a single contiguous memory region for the header and payload elements.
3
p->payload[i] = data[i];
Accesses payload memory directly adjacent to header fields without extra indirection.