Where should the decoder keep a partial frame between calls? One natural design is a growable buffer: read the declared length from the header, malloc that many bytes, and realloc as data arrives. It handles any length, which sounds like a feature. In practice it lets the input decide how much memory your program allocates. A sender that declares 65535-byte payloads on every frame, then never finishes them, makes the decoder allocate and hold memory on demand. Every malloc in the feed path is also a new failure path: what should decoder_feed report when it runs out of memory halfway through a frame?
The project avoids both problems by fixing the storage at compile time. The Decoder struct contains an array large enough for the biggest frame the protocol allows:
struct Decoder {
unsigned char frame[5 + TELEMETRY_PAYLOAD_LIMIT + 1]; /* header + payload limit + checksum */
size_t used;
int failed;
TelemetryAllocator allocator;
};The array is allocated once, as part of the struct, when decoder_create runs. After that, decoder_feed, decoder_finish and decoder_reset never allocate. They cannot fail for lack of memory, they cannot leak, and their memory use is the same for the first frame and the millionth.
Predict and run
Read the program before pressing Run. Predict the storage size, then explain why a declared payload of 65535 must be rejected before any payload byte is buffered.
#include <stdio.h>
int main(void) {
size_t header = 5, payload_limit = 16, checksum = 1;
printf("Storage: %zu\n", header + payload_limit + checksum);
return 0;
}Check your prediction
Storage: 22Twenty-two bytes hold the largest legal frame. A declared payload of 65535 would need 65541, so if the decoder started copying payload bytes before checking, the 18th byte of the oversized payload would already be past the array's end: the payload starts at offset 5, and offsets 5 to 21 are all the array has. The header arrives before the payload, which gives the decoder exactly one safe moment to reject it: when byte 5 lands.
The limit is a protocol decision
Only one frame type exists today, and its payload is exactly 4 octets, so the decoder never actually uses more than 10 of its 22 bytes. The 16-byte limit is a defensive bound written into the protocol: no future type may exceed it, so the storage never needs to change size. Accepting a type is a separate decision, made by the header check. A limit is a promise about memory; it is not a promise to accept every length up to that limit.
Because the array size is a compile-time constant, the compiler can check relationships that must hold. A static assertion fails the build, instead of a test or a user, if someone later shrinks the buffer below what a valid frame needs:
#include <stdio.h>
#define PAYLOAD_LIMIT 16
#define FRAME_SIZE 10
typedef struct { unsigned char frame[5 + PAYLOAD_LIMIT + 1]; size_t used; } Buffer;
_Static_assert(sizeof ((Buffer *)0)->frame >= FRAME_SIZE, "buffer must hold a reading frame");
int main(void) {
Buffer b = {{0}, 0};
printf("capacity %zu, reading frame %d, spare %zu\n", sizeof b.frame, FRAME_SIZE,
sizeof b.frame - FRAME_SIZE);
return 0;
}capacity 22, reading frame 10, spare 12sizeof ((Buffer *)0)->frame never dereferences the null pointer. sizeof does not evaluate its operand; it only needs the type, so this is a standard way to ask for a member's size without an object. Change PAYLOAD_LIMIT to 2 and the build stops with the assertion's message.
Check capacity without overflowing
Whenever code appends to a fixed buffer, it needs the Day 2 check in its capacity form. used + incoming <= capacity can wrap if incoming is huge. The safe form first proves used <= capacity, which should always hold but costs nothing to check, and only then compares incoming with the space that remains:
#include <stdio.h>
#include <stdint.h>
int fits_capacity(size_t used, size_t incoming, size_t capacity) {
return used <= capacity && incoming <= capacity - used;
}
int main(void) {
printf("5 + 17 in 22: %d\n", fits_capacity(5, 17, 22));
printf("5 + 18 in 22: %d\n", fits_capacity(5, 18, 22));
printf("5 + huge in 22: %d (naive sum says %d)\n", fits_capacity(5, SIZE_MAX, 22),
5 + SIZE_MAX <= 22);
return 0;
}5 + 17 in 22: 1
5 + 18 in 22: 0
5 + huge in 22: 0 (naive sum says 1)The first clause also turns a corrupted used, perhaps from a bug elsewhere, into a refusal instead of an out-of-bounds write. The decoder itself checks one byte at a time and relies on the header check, so used never exceeds 10, but any multi-byte append into fixed storage should use this shape. Appends should also be all-or-nothing: if the whole chunk does not fit, copy none of it, so the caller never has to work out which part was stored.
Practice
Your turn
fits_capacity answers all-or-nothing appends. A streaming decoder needs the other policy: take as much as fits and report how much that was, so the caller keeps the rest, exactly like consumed. Write size_t append_some(Buffer *b, const unsigned char *bytes, size_t n) for the 22-octet buffer. It copies the first min(n, room) octets, returns that count, and never calls memcpy with a count of 0. A buffer whose used is already past its capacity takes nothing. The starter must print:
offer 5: took 5, left 0, used 5
offer 18: took 17, left 1, used 22
offer 17: took 0, left 17, used 22
offer 0: took 0, left 0, used 22
corrupt used 23: took 0, used 23#include <stdio.h>
#include <string.h>
typedef struct { unsigned char frame[22]; size_t used; } Buffer;
/* Write append_some here:
size_t append_some(Buffer *b, const unsigned char *bytes, size_t n); */
int main(void) {
const unsigned char data[18] = {0};
Buffer b = {{0}, 0};
const size_t sizes[4] = {5, 18, 17, 0};
for (size_t i = 0; i < 4; ++i) {
size_t took = append_some(&b, data, sizes[i]);
printf("offer %zu: took %zu, left %zu, used %zu\n", sizes[i], took, sizes[i] - took, b.used);
}
b.used = 23;
printf("corrupt used 23: took %zu, used %zu\n", append_some(&b, data, 1), b.used);
return 0;
}Hint 1: the idea
The room left is a subtraction, and a subtraction of sizes is only safe once you know it cannot go below zero. Settle that first; after it, the count to take is the smaller of two numbers, and the copy and the update of used happen together.
Hint 2: a first step
Write the room computation without any guard and only print it for the corrupt case before writing the rest: with used 23 and capacity 22, what does it print? That number is why the guard has to come before the subtraction. Then add the guard, and write the rest for the four ordinary offers.
Show one solution
#include <stdio.h>
#include <string.h>
typedef struct { unsigned char frame[22]; size_t used; } Buffer;
/* Copies as many of the n octets as fit and returns that count.
A corrupted buffer (used past capacity) takes nothing. */
size_t append_some(Buffer *b, const unsigned char *bytes, size_t n) {
size_t capacity = sizeof b->frame;
if (b->used >= capacity) { return 0; }
size_t room = capacity - b->used;
size_t take = n < room ? n : room;
if (take > 0) { memcpy(b->frame + b->used, bytes, take); }
b->used += take;
return take;
}
int main(void) {
const unsigned char data[18] = {0};
Buffer b = {{0}, 0};
const size_t sizes[4] = {5, 18, 17, 0};
for (size_t i = 0; i < 4; ++i) {
size_t took = append_some(&b, data, sizes[i]);
printf("offer %zu: took %zu, left %zu, used %zu\n", sizes[i], took, sizes[i] - took, b.used);
}
b.used = 23;
printf("corrupt used 23: took %zu, used %zu\n", append_some(&b, data, 1), b.used);
return 0;
}offer 5: took 5, left 0, used 5
offer 18: took 17, left 1, used 22
offer 17: took 0, left 17, used 22
offer 0: took 0, left 0, used 22
corrupt used 23: took 0, used 23The second offer is the interesting one: 17 of 18 octets fit, and the caller learns that 1 is left over, instead of the all-or-nothing refusal fits_capacity would give. The guard compares with >=, so a full buffer also returns early and the 0-octet memcpy question never arises for it. The decoder's consumed is this function's return value, one octet at a time.
Prove it can fail
Delete the guard and run under UndefinedBehaviorSanitizer if you can. The corrupt line becomes took 1, used 24: 22 - 23 wrapped to the largest size_t, so the room looked enormous and one octet was written past the end of frame, which the sanitizer reports as an out-of-bounds index. That is the wrap fits_capacity avoids with its first clause.
Completion is saved in this browser only. It does not measure mastery.