Simvik

Fix: old payload bytes leak into new packets

A packet is only partly cleared before it is reused. An easy embedded C problem (Structs, unions and memory layout), run and graded in the browser.

easy · Structs, unions and memory layout · find-the-bug · sizeof · memset

Bug report. When the radio driver reuses a packet, the receiver sometimes sees bytes from the previous message at the end of the payload. The type, len and seq fields always arrive cleared.

packet_clear must set every byte of the packet to zero, and nothing outside it. Find the defect and fix it by changing one line.

Starter code

void packet_clear(packet_t *p) {
  memset(p, 0, sizeof(p));
}

Example tests

Clear a packet full of old data

packet_t p;
memset(&p, 0xAA, sizeof p);
packet_clear(&p);
printf("type=%u len=%u seq=%u\n", p.type, p.len, p.seq);
printf("payload=");
for (int i = 0; i < 12; i++) printf("%02X", p.payload[i]);
printf("\n");

Expected output:

type=0 len=0 seq=0
payload=000000000000000000000000

Learn it first

More Structs, unions and memory layout problems