Make a driver function MISRA compliant
Working code that the project's MISRA checker rejects: fix every finding without changing what it does. An easy embedded C problem (Static analysis and MISRA…
easy · Static analysis and MISRA in practice · misra · static-analysis · coding-standards · essential-types
status_bits works, and its tests would pass, but this is a safety project: the build runs a MISRA C checker, and any finding fails it. The checker is part of this problem, and the rules it enforces are listed below.
status_bits(flags, mode) builds a status byte: bit 4 if flags bit 0 is set, bit 5 if flags bit 7 is set, and then bit 0 for mode 0, or bit 1 for modes 1 and 2. Other modes add nothing.
Press Run to see the findings. Then change the code until there are none, and the tests still pass.
Starter code
uint8_t status_bits(uint8_t flags, int32_t mode) {
uint8_t out = 0;
if (flags & 0x01) out |= 0x10;
if (flags & 0x80) out |= 0x20;
switch (mode) {
case 0: out |= 1; break;
case 1:
case 2: out |= 2; break;
}
return out;
}Example tests
Each flag and mode
show(0x00, 0);
show(0x01, 1);
show(0x80, 2);
show(0x81, 5);Expected output:
flags 0x00, mode 0: 0x01
flags 0x01, mode 1: 0x12
flags 0x80, mode 2: 0x22
flags 0x81, mode 5: 0x30Learn 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.
- 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.
- 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.