C struct layout is not a binary serialization format
A program may have a clean struct representing sensor metadata. Its in-memory layout is chosen according to the C implementation and ABI. Padding may exist between fields and at the end. Sending sizeof that structure bytes across a protocol therefore couples the receiver to details that the protocol may not specify, and padding can contain unintended data.
The contract
Define the wire format independently. In the tiny example, a 16-bit value is encoded in two bytes in big-endian order followed by an eight-bit tag. Explicit writes determine every byte. The struct is still useful inside the program; it just no longer dictates the external representation.
A small executable example
#include <stdint.h>
#include <assert.h>
#include <stdio.h>
struct item { uint16_t value; uint8_t tag; };
static void encode(uint8_t dst[3], struct item x) {
dst[0] = (uint8_t)((uint32_t)x.value >> 8);
dst[1] = (uint8_t)x.value;
dst[2] = x.tag;
}
int main(void) {
uint8_t out[3];
encode(out, (struct item){0x1234, 7});
assert(out[0] == 0x12 && out[1] == 0x34 && out[2] == 7);
printf("%02x %02x %02x\n", (unsigned)out[0], (unsigned)out[1], (unsigned)out[2]);
}
12 34 07
Compiled with -Wall -Wextra -Werror and run under AddressSanitizer + UBSan.
Learning this for work or an interview? Lessons 1 and 2 of DSA for Firmware are free, with labs and C exercises. Start Lesson 1
What the example does not establish
The array syntax on the parameter does not validate that the destination has three bytes. The caller must fulfill that precondition, or the API should accept and check a capacity. A production protocol may include versioning, checksums and lengths. A packed struct alone does not solve endianness or portable unaligned access, and it can introduce additional implementation assumptions.
Checks to add in your own project
Check exact serialized bytes against independent fixtures, not only an encode/decode round trip that could hide a symmetric error. Include minimum and maximum field values, reserved bits and malformed messages in decoder tests. On each target, use the appropriate compiler and confirm whether the assumptions of the in-memory struct are relevant to any other interface. The external format should remain stable even if you change the internal representation.
DSA for Firmware teaches it one real bug at a time.
- 28 lessons, each starting from a real firmware bug.
- 110 C exercises with tests, and a reference solution for every one.
- Lessons 1 and 2 are free. No sign-up.
Get the next article by email
One short email when a new article or free lesson is published. No spam. Unsubscribe at any time by replying to any email. See the privacy policy.