Review: an error path keeps the bus lock
After one failed sensor read, every later read on the shared bus deadlocks. An easy embedded C problem (Code review for embedded C), run and graded in the…
easy · Code review for embedded C · find-the-bug · code-review · error-handling · mutex
Review comment. "The first error path returns without releasing the bus. After a single failed read of register 0x10, the bus stays locked and the next task that needs it hangs forever."
sensor_read_pair reads two registers under the bus lock. Fix the leak so that every return releases the lock, changing at most three lines.
Starter code
int sensor_read_pair(uint8_t *hi, uint8_t *lo) {
bus_lock();
if (bus_read(0x10, hi) != 0) return -1;
if (bus_read(0x11, lo) != 0) {
bus_unlock();
return -1;
}
bus_unlock();
return 0;
}Example tests
The first read fails, then a normal read
attempt(1);
attempt(0);Expected output:
-1 00 00 locked=0
0 30 31 locked=0Learn 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: sizeof on an array parameter · A function meant to clear a receive buffer only clears its first few bytes.
- Review: a timeout that breaks after 49 days · A deadline check adds to a 32-bit millisecond tick, which wraps.
- 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.