Simvik

Fix: the receiver rejects every header

A header is serialised by copying a struct whose padding does not match the wire format. A medium embedded C problem (Structs, unions and memory layout), run…

medium · Structs, unions and memory layout · find-the-bug · padding · packed · serialisation

Bug report. The wire format of a message header is 7 bytes: type (1 byte), then seq (4 bytes) and len (2 bytes), both little-endian, with no gaps. encode_header copies a struct into the output buffer, but the receiver rejects every header: the length it gets is wrong and the sequence number is garbage. Fix it by changing one line. The target is little-endian, like the wire format.

Starter code

typedef struct {
  uint8_t  type;
  uint32_t seq;
  uint16_t len;
} hdr_t;

int encode_header(uint8_t *out, uint8_t type, uint32_t seq, uint16_t len) {
  hdr_t h = { type, seq, len };
  memcpy(out, &h, sizeof h);
  return sizeof h;
}

Example tests

Encode one header

uint8_t out[16];
int n = encode_header(out, 0x01, 0x04030201, 0x0605);
printf("%d:", n);
for (int i = 0; i < n; i++) printf(" %02X", out[i]);
printf("\n");

Expected output:

7: 01 01 02 03 04 05 06

Learn it first

More Structs, unions and memory layout problems