Parse Binary Protocols Safely Without Undefined Behaviour
Avoid the four classic undefined-behaviour traps in C binary parsers: unaligned casts, signed shifts, overflowing bounds checks and attacker-controlled lengths.

A binary protocol parser is a function that takes bytes from an attacker and turns them into decisions, which makes it one of the most dangerous pieces of code in a network program. In C the danger has a second layer: the language lets perfectly natural-looking code invoke undefined behaviour, and the compiler is entitled to assume that never happens and optimise accordingly. A bounds check that "obviously" works gets deleted. This post covers the four traps that account for most real parser bugs, with a checked reader you can reuse. It assumes C17 compiled with GCC 14 or Clang 19, and some comfort with pointers.
Trap one: casting a byte pointer to an integer pointer
The most natural way to read a 32-bit field from a buffer is to cast and dereference:
uint32_t length = *(uint32_t *)(buf + 4); /* wrong */It has two separate problems. The address buf + 4 is not guaranteed to be aligned for a uint32_t, and an unaligned access is undefined behaviour in C even on hardware that tolerates it, because the compiler may emit an instruction that assumes alignment. On x86 it usually works until the optimiser vectorises a loop around it. On some ARM cores and many embedded targets it faults. Separately, reading a char array as uint32_t breaks the strict aliasing rule in C17 6.5, so the compiler may reorder the read against writes to the array.
The correct, portable read copies the bytes into a properly typed object. A fixed-size memcpy is recognised by every mainstream compiler and compiles to a single load where the target allows it.
#include <stdint.h>
#include <stdio.h>
#include <string.h>
static uint32_t read_be32(const uint8_t *p)
{
return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) |
((uint32_t)p[2] << 8) | (uint32_t)p[3];
}
int main(void)
{
uint8_t buf[] = { 0xff, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x00 };
printf("0x%08x\n", read_be32(buf + 4));
return 0;
}0x80000000The function assembles the value from single bytes, so it needs no alignment and no byte-swap helper, and it gives the same answer on every host. That also removes the endianness question from the call site, because the byte order is stated in the function's name and body.
Trap two: shifting into the sign bit
The reader above has a detail that is easy to miss. Each byte is cast to uint32_t before the shift. Without the cast, p[0] << 24 promotes p[0] to int, and shifting a value of 128 or more left by 24 places moves a bit into the sign bit of a 32-bit int. C17 6.5.7 makes that undefined behaviour for a signed type when the result is not representable. A length byte of 0x80 is exactly the value an attacker will choose.
Compare the two forms side by side:
#include <stdint.h>
#include <stdio.h>
int main(void)
{
uint8_t p[4] = { 0x80, 0x00, 0x00, 0x00 };
uint32_t good = (uint32_t)p[0] << 24; /* defined: unsigned arithmetic */
/* int bad = p[0] << 24; undefined: 128 << 24 overflows int */
printf("good = %u\n", good);
return 0;
}good = 2147483648UBSan reports the bad form at run time with a message of the form left shift of 128 by 24 places cannot be represented in type 'int'. Building tests with -fsanitize=undefined is the cheapest way to find this class of bug, and the post on libFuzzer later in this series shows how to feed it hostile input.
Trap three: a bounds check that overflows
The next trap hides inside the check meant to protect you. A parser reads an offset and a length from the packet, then checks they fit:
if (offset + length > buf_len) /* wrong: the sum can wrap */
return -1;If offset and length are uint32_t read from the wire, an attacker sends offset = 0xfffffff0 and length = 0x20. The sum wraps to 0x10, which is less than buf_len, so the check passes, and the subsequent read goes far outside the buffer. With signed integers it is worse, since the overflow is itself undefined behaviour and a compiler may fold the whole comparison away.
Rewrite the check as a subtraction against a value you know is non-negative, so nothing can overflow:
#include <stdint.h>
#include <stdio.h>
/* True if [offset, offset + length) lies inside a buffer of size total. */
static int in_bounds(size_t total, size_t offset, size_t length)
{
return offset <= total && length <= total - offset;
}
int main(void)
{
size_t total = 64;
printf("%d\n", in_bounds(total, 8, 16));
printf("%d\n", in_bounds(total, 60, 8));
printf("%d\n", in_bounds(total, 0xfffffff0u, 0x20));
return 0;
}1
0
0total - offset cannot underflow, because the first half of the condition has already established offset <= total. The short-circuit && guarantees the subtraction runs only then. This pattern, check the first quantity against the total and the second against what remains, is the one to memorise.
Trap four: trusting a length to allocate or loop
The last trap is not undefined behaviour but a logic failure that the others enable. A length field from the wire must never drive an allocation or a loop count until it has been compared with a limit you chose. malloc(count * sizeof(struct entry)) with an attacker-chosen count can overflow the multiplication, producing a small buffer that the loop then overruns. Check count <= MAX_ENTRIES first, and check that count entries fit in the remaining bytes, before doing any arithmetic with it.
A reader that makes the right thing the easy thing
Rather than remember four rules at every field, put them in one small type. The reader carries a pointer and a remaining length, every accessor checks before it reads, and a sticky error flag means you can read several fields and test once at the end.
#ifndef READER_H
#define READER_H
#include <stddef.h>
#include <stdint.h>
#include <string.h>
struct reader {
const uint8_t *p;
size_t left;
int ok;
};
static inline void reader_init(struct reader *r, const void *buf, size_t n)
{
r->p = buf;
r->left = n;
r->ok = 1;
}
static inline int reader_take(struct reader *r, size_t n)
{
if (!r->ok || n > r->left) {
r->ok = 0;
return 0;
}
return 1;
}
static inline uint8_t reader_u8(struct reader *r)
{
if (!reader_take(r, 1))
return 0;
uint8_t v = r->p[0];
r->p += 1;
r->left -= 1;
return v;
}
static inline uint16_t reader_be16(struct reader *r)
{
if (!reader_take(r, 2))
return 0;
uint16_t v = (uint16_t)((r->p[0] << 8) | r->p[1]);
r->p += 2;
r->left -= 2;
return v;
}
static inline const uint8_t *reader_bytes(struct reader *r, size_t n)
{
if (!reader_take(r, n))
return NULL;
const uint8_t *out = r->p;
r->p += n;
r->left -= n;
return out;
}
#endifreader_take compares n > r->left, a single comparison with no addition, so it cannot overflow. In reader_be16 the expression r->p[0] << 8 promotes to int, but the largest result is 255 shifted by 8, which is 65280 and fits comfortably, so no sign bit is touched. On failure every accessor returns zero and leaves the cursor alone, which keeps later reads from using a half-consumed position.
Here it is parsing a type-length-value record, a shape that appears in countless protocols:
#include "reader.h"
#include <stdio.h>
int main(void)
{
/* type 1, length 5, "hello"; then a record that claims 200 bytes */
const uint8_t wire[] = { 0x01, 0x00, 0x05, 'h', 'e', 'l', 'l', 'o',
0x02, 0x00, 0xc8, 'x' };
struct reader r;
reader_init(&r, wire, sizeof wire);
for (int i = 0; i < 2; i++) {
uint8_t type = reader_u8(&r);
uint16_t len = reader_be16(&r);
const uint8_t *value = reader_bytes(&r, len);
if (!r.ok) {
printf("record %d: truncated\n", i);
return 1;
}
printf("record %d: type %u, %u bytes: %.*s\n",
i, type, len, (int)len, (const char *)value);
}
return 0;
}record 0: type 1, 5 bytes: hello
record 1: truncatedThe second record declares 200 bytes while only one remains, so reader_bytes fails and the sticky flag reports it. The parser never reads past the buffer, and it never computes offset + length.
Make the compiler and the tools help
Turn on the checks that find these bugs before an attacker does. Compile tests with -fsanitize=address,undefined, which catches out-of-bounds reads and misaligned or overflowing operations at run time. Add -Wall -Wextra -Wconversion to flag silent narrowing such as assigning a size_t to a uint16_t. And fuzz the parser, because a human writing test inputs does not think of 0xfffffff0.
When this is not enough
The reader makes memory errors unlikely, not logic errors. A parser can read every byte safely and still accept a message that violates the protocol, such as overlapping regions or a count that disagrees with the data. Validation of meaning, as opposed to bounds, is a separate step and needs its own checks. If the format is complex and the stakes are high, a memory-safe language or a generated parser removes the entire category of trap described here.

