Review: a timeout that breaks after 49 days
A deadline check adds to a 32-bit millisecond tick, which wraps. An easy embedded C problem (Code review for embedded C), run and graded in the browser.
easy · Code review for embedded C · find-the-bug · code-review · timing · overflow
Review comment. "start + timeout overflows when the tick is close to 2³², which happens every 49.7 days of uptime. Right after that, now >= start + timeout is true straight away, and every timeout fires early. Compare elapsed time instead."
now is the free-running millisecond tick (uint32_t, wraps to 0). Fix expired by changing one line, so it is right across the wrap, for any timeout shorter than 49 days.
Starter code
bool expired(const deadline_t *d, uint32_t now) {
return now >= d->start + d->timeout;
}Example tests
Early in uptime, then just before the wrap
check(1000, 500, 1200);
check(1000, 500, 1500);
check(0xFFFFFF00u, 0x200, 0xFFFFFF80u);Expected output:
start 0x000003E8 + 500 ms, now 0x000004B0: waiting
start 0x000003E8 + 500 ms, now 0x000005DC: expired
start 0xFFFFFF00 + 512 ms, now 0xFFFFFF80: waitingLearn it first
- Code review for embedded C · What to look for in firmware changes, how to comment, and what to leave to tools.
More Code review for embedded C problems
- Review: a length from the packet is trusted · A message decoder copies as many bytes as the packet says, into a fixed-size buffer.
- Review: an error path keeps the bus lock · After one failed sensor read, every later read on the shared bus deadlocks.
- Review: sizeof on an array parameter · A function meant to clear a receive buffer only clears its first few bytes.
- Review: the ring buffer grew to 100 bytes · A change resized a ring buffer, but its index wrap still uses a bit mask.
- Review: blocks got bigger than the loop counter · A checksum loop uses a uint8_t index, and the block size was raised past 255.
- Review: the sensor's temperature is read in the wrong byte order · A driver copies a big-endian signed field straight into a little-endian int16_t.
- Review: strncpy does not always terminate · A setter copies a name with strncpy, and a long name leaves the field without a terminator.