Fix: a short frame is read past its end
A length check compares a negative int with sizeof, which converts it to a huge unsigned value. A medium embedded C problem (Static analysis and MISRA in…
medium · Static analysis and MISRA in practice · find-the-bug · static-analysis · misra · signed-unsigned · buffer-overflow
Analyser finding (suppressed). "Rule 10.4: both operands of an operator in which the usual arithmetic conversions are performed shall have the same essential type category." GCC adds "comparison of integer expressions of different signedness" (-Wsign-compare).
payload_len(buf, n) returns the payload length of the n bytes received so far, or -1 if the length field has not arrived yet or the payload is incomplete. When fewer than HDR_LEN bytes have arrived, remaining is negative, the comparison converts it to size_t, and the code reads past the end of buf. Fix it by changing one line.
Starter code
int payload_len(const uint8_t *buf, int n) {
int remaining = n - HDR_LEN;
if (remaining < sizeof(uint16_t)) return -1;
int len = buf[HDR_LEN] | (buf[HDR_LEN + 1] << 8);
if (len > remaining - 2) return -1;
return len;
}Example tests
A complete frame, then one with only 2 bytes so far
uint8_t f[] = { 0xAA, 0x01, 0x00, 0x00, 3, 0, 'a', 'b', 'c' };
check(f, 9);
check(f, 2);Expected output:
9 bytes: 3
2 bytes: -1Learn it first
- Static analysis and MISRA in practice · Warnings worth enabling, the essential type model, common MISRA findings, deviations and legacy code.
More Static analysis and MISRA in practice problems
- Fix: the energy counter loses energy · An energy meter multiplies in 32 bits and only then adds to a 64-bit total.
- Fix: the modem is not reset when it should be · A counter inside the right side of && only counts some of the time.
- Fix: turning the LED off reboots the device · A missing break makes one command fall through into the next.
- Fix: the search that never stops · A countdown loop with an unsigned index has a condition that is always true.
- Fix: faults above 31 cannot be set or cleared · A 64-bit fault mask is updated with 32-bit shifts, and clearing one fault clears thirty-two.
- Fix: settings that say they saved, but did not · A settings save ignores the return values of the flash erase and write.
- Make a driver function MISRA compliant · Working code that the project's MISRA checker rejects: fix every finding without changing what it does.
- No recursion, no heap · Rewrite a recursive function and a heap-using function to fit a safety-critical project's rules.
- Essential types in sensor maths · Make three small sensor functions pass MISRA's essential type rules, without changing their results.