Simvik

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: waiting

Learn it first

More Code review for embedded C problems