Try Embedded

Static analysis and MISRA in practice

Warnings worth enabling, the essential type model, common MISRA findings, deviations and legacy code.

From a list of warnings to safer code

Turning on a static analyser on an existing project typically produces hundreds or thousands of findings. The skill is not running the tool; it is working through its output: deciding which findings are real bugs, fixing them in a way that does not add new ones, and recording the rest so the list stays clean. This lesson is about that work. Safety and security standards explains what MISRA C is and why it exists, and Testing and code coverage lists the tools.

Compiler warnings come first

The compiler is the analyser you already have. A good baseline for C firmware with GCC or Clang:

FlagWhat it finds
-Wall -WextraThe common set: unused variables, missing returns, suspicious comparisons
-Wconversion and -Wsign-conversionImplicit conversions that can change a value: int to uint8_t, signed to unsigned
-WshadowA local that hides another variable of the same name
-Wdouble-promotionA float silently promoted to double, slow on a single-precision FPU
-Wimplicit-fallthroughA switch case that falls into the next one without saying so
-Wcast-align, -Wpointer-arithCasts that create misaligned pointers, arithmetic on void *
-Wformat=2, -Wundef, -Wstrict-prototypesBad printf formats, undefined macros in #if, functions declared without parameter types

Add -Werror in CI once the code is clean, so new warnings cannot be merged.

The essential type model

Many MISRA rules and -Wconversion warnings are about the same thing: C converts integer types silently, and the result is often not what the code seems to say. Operands narrower than int are promoted to int before arithmetic, and mixing signed and unsigned converts the signed one to unsigned.

#include <stdio.h>
#include <stdint.h>

int main(void) {
  uint8_t a = 200, b = 100;
  uint16_t x = 60000u;
  uint32_t us = 5000000u;

  /* Promotion: two uint8_t are added as int, so the sum is 300, not 44. */
  printf("a + b = %d, sizeof(a + b) = %d\n", a + b, (int)sizeof(a + b));
  uint8_t stored = (uint8_t)(a + b);           /* narrowing must be explicit; it wraps to 44 */
  printf("stored in a uint8_t: %u\n", (unsigned)stored);

  /* Signed meets unsigned: -1 becomes 4294967295 and the comparison flips. */
  int32_t n = -1;
  printf("n < 1u is %s\n", (uint32_t)n < 1u ? "true" : "false");

  /* Widening after the fact is too late: the multiply is done in 32 bits and wraps. */
  uint64_t ns_wrong = us * 1000u;
  uint64_t ns_right = (uint64_t)us * 1000u;    /* widen one operand first */
  printf("ns wrong %llu, right %llu\n", (unsigned long long)ns_wrong, (unsigned long long)ns_right);

  /* x * x is int * int here: 60000 * 60000 would overflow int, which is undefined behaviour. */
  uint32_t sq = (uint32_t)x * x;
  printf("x squared %lu\n", (unsigned long)sq);
  return 0;
}

MISRA C calls this the essential type model: it treats each expression as having an essential type (Boolean, character, signed, unsigned, enum, floating) and restricts how they mix. The fixes are almost always the same few habits: widen before the operation, keep signed and unsigned apart, make every narrowing explicit, and use U suffixes on unsigned constants.

Findings you will see most

Rule numbers are from MISRA C:2012, which MISRA C:2023 keeps.

RuleSaysTypical fix
10.3No assignment to a narrower or different essential typeExplicit cast after checking the range, or a wider variable
10.4Both operands of an arithmetic or comparison operator in the same categoryCast one side, or change a variable's type
10.8A composite expression must not be cast to a wider typeCast an operand, not the result: (uint64_t)a * b
12.1Make operator precedence explicit (advisory)Parentheses: (flags & MASK) != 0u
13.5No persistent side effects on the right of && or ||Move i++ or the function call to its own statement
14.4if and loop conditions must be essentially Booleanif (ptr != NULL), if (count > 0u)
15.7if ... else if chains end with elseAdd else with a comment or an error report
16.3 and 16.4Every switch clause ends in break; every switch has defaultAdd them; make intended fall-through explicit
17.7Do not ignore a function's return valueCheck it, or cast to (void) to show it is deliberate
21.3No malloc and freeStatic allocation or fixed-size pools
11.4Do not convert between integers and pointers (advisory)Unavoidable for registers: one documented deviation

Deviations: when the rule is right in general but wrong here

Some code must break a rule. Every register access converts an integer address to a pointer, against Rule 11.4. MISRA allows a deviation: a documented, reviewed decision that names

  1. the rule and exactly where it is deviated (one macro, one file),
  2. why compliance is not possible or would make the code worse,
  3. how the risk is controlled (here: addresses come only from the vendor's device header),
  4. who approved it.

In the code, the deviation is referenced by a tool-specific comment so the analyser stops reporting it, for example // cppcheck-suppress misra-c2012-11.4 or // NOLINT(performance-no-int-to-ptr) for clang-tidy, each pointing at the deviation record. Suppressing a finding without a record is not a deviation; it is hiding the finding.

Bringing old code under analysis

Fixing three thousand findings in one go rarely happens, and mass-editing working code to please a tool can add real bugs. A workable approach:

  1. Fix everything the tool calls a likely bug (null dereference, buffer overrun, uninitialised read, undefined behaviour) first.
  2. Record the remaining findings as a baseline and fail CI only on new ones. The count can only go down.
  3. Clean up a file properly when you next change it for another reason.
  4. For true false positives, suppress them with a comment that says why.

Pitfall: "Fixing" a conversion warning by adding a cast silences the tool without making the code correct. Before casting, decide what should happen when the value does not fit, and handle that case.

Interview question: How do you introduce MISRA or a static analyser on a large existing codebase?

Answer: Run it once to see the scale, then fix the findings that indicate real defects first: undefined behaviour, overruns, null dereferences, uninitialised reads. Record everything else as a baseline and make CI fail only on new findings, so the number can only fall. Agree on deviations for rules the project cannot follow, such as integer-to-pointer casts for registers, documented once and referenced where used. Clean up files properly when they are next changed, rather than mass-editing working code, which risks adding bugs to satisfy the tool.

Build it: pass the MISRA check before release

This is step 3 of the module project. The customer runs these sensors in plants with safety certification, and the contract requires the firmware to follow MISRA C:2012. The alarm-level code below works, and every test passes, but the static analyser in the release build rejects it. Make it compliant without changing what it does.

Lab: Make working code MISRA C compliant

The code classifies the vibration level by the ISO 10816 style zones, and logs an event whenever the level changes:

RMSLevel
below 2000 mgLVL_GOOD
2000 to 3999 mgLVL_WATCH
4000 to 7999 mgLVL_ALARM
8000 mg and aboveLVL_TRIP

level_update(rms, last) stores the new level in *last and returns true when it changed, calling the provided log_event() for each change. log_event returns false when the log is full; the code may ignore that, but it must say so explicitly.

Your code is checked against the rules listed under Coding standard before any test runs, and each finding is an error with its line, as in a certified project's build. Typical fixes: braces around every if, else and loop body; a default in every switch; a break ending every case; conditions that are real booleans (x != 0u, not x); and (void) in front of a call whose result you deliberately ignore.

Going deeper

Interview question: How would you introduce MISRA C and static analysis to an existing automotive codebase?

Answer: Run the analyser on everything to get a baseline, then require new and changed code to be clean while burning down the existing findings by priority. Agree on documented deviations for rules that do not fit, run the analysis in CI on every change, and review the findings in code review rather than in bulk.

Interview question: What is a MISRA deviation, and what must one contain?

Answer: A deviation is an approved, documented decision to not follow a Required or Advisory guideline in a specific place, because following it is impossible or would make the code worse. It records which rule, exactly where it applies, the justification, how the risk is managed and who approved it, and the code points to it with an analyser suppression comment. Mandatory guidelines cannot be deviated. Without that record, a suppressed warning is just a hidden finding, and an assessor will treat it that way.

Interview question: Why does if (ready && (count++ < LIMIT)) violate MISRA Rule 13.5, and what bug can it cause?

Answer: The right operand of && is evaluated only when the left one is true, so count is incremented only on some calls. A reader, or a later edit that reorders the conditions, easily assumes count changes every time. If count is meant to track attempts or time, it silently undercounts while ready is false. Rule 13.5 requires side effects to be moved out of the right operand, into their own statement, so they always happen exactly when the code says.

Explain it: In your own words, explain the essential type model and the habits that satisfy it.

Answer: C silently converts integers: values narrower than int are promoted to int before arithmetic, mixed signed and unsigned operands convert the signed one to unsigned, and assigning to a smaller type drops bits. MISRA's essential type model gives every expression a category such as unsigned, signed or Boolean and forbids mixing categories or narrowing implicitly. In practice that means widening an operand before a multiply that could overflow, keeping signed and unsigned values out of the same expression, writing explicit casts only after deciding what happens when a value does not fit, using U on unsigned constants, and writing conditions as real comparisons.