Try Embedded

MISRA C on a real project

Guidelines and their categories, the rules that change how you write, deviations, and compliance claims.

What this lesson adds

Static analysis and MISRA in practice (in the engineering module) covers the essential type model and the findings you meet most. This lesson is about working on a project where MISRA compliance is a contractual deliverable: how the standard is organised, which rules shape the structure of your code rather than its details, how deviations and compliance claims work, and how to write a diagnostic handler that passes the checker the first time.

In automotive work this is not optional knowledge. ISO 26262 part 6 asks for "use of language subsets" at every integrity level, car makers name MISRA C in their supplier requirements, and AUTOSAR's own code is written to it. An interviewer who asks "have you worked with MISRA?" wants to hear about process as much as about rules.

How the standard is organised

MISRA C:2012 (now consolidated with its amendments as MISRA C:2023, which also covers C11 and C18) contains about 200 guidelines of two kinds:

  • A rule is a statement about the source code that can be checked from the code alone. Rule 15.6: the body of an iteration-statement or a selection-statement shall be a compound-statement.
  • A directive needs information beyond the code, such as design documents or the compiler's manual. Directive 4.1: run-time failures shall be minimised. A tool can help with a directive but cannot settle it.

Each guideline has a category:

CategoryMeaningCan you deviate?
Mandatorymust always be followednever
Requiredmust be followedonly with a formal, approved deviation
Advisoryshould be followedmay be set aside, with the decision documented (the project may choose a lighter process)

And each rule has two properties that tell you how far to trust a tool's verdict on it:

PropertyValuesWhy it matters
Decidabilitydecidable: a tool can always answer yes or no. Undecidable: the answer may depend on run-time valuesFor an undecidable rule (for example 9.1, reading an uninitialised object, or 18.1, pointer arithmetic staying in bounds) a tool reports possible violations and can miss real ones. A clean report is not proof
Scope of analysissingle translation unit or systemA system rule (for example 8.6, one definition for each external identifier) can only be checked by analysing the whole program together. Per-file analysis in a pre-commit hook does not cover it

The guidelines are grouped by subject. Knowing the groups lets you find a rule without memorising numbers:

GroupSubjectExample
2unused code2.2 no dead code
8declarations and definitions8.4 a compatible declaration visible at a definition; 8.7 no external linkage for something used in one file
10the essential type model10.3 no assignment to a narrower or different essential type
11pointer conversions11.4 no conversion between a pointer to object and an integer
12, 13expressions and side effects13.5 no side effects on the right of && and ||
14, 15, 16control flow, switch15.5 single exit; 16.4 a default in every switch
17functions17.2 no recursion; 17.7 use every returned value
18pointers and arrays18.4 no + or - on pointers
21the standard library21.3 no malloc and free; 21.6 no standard I/O

The rules that change how you structure code

Most findings in a new code base are essential-type details: a missing U suffix, an implicit narrowing. They are tedious and mechanical. A handful of rules instead decide the shape of every function, and are far cheaper to follow from the first line than to retrofit.

Rule 15.5 (advisory): a function should have a single point of exit at the end. Early returns are how most people write checks:

if (len != 3U) { return NRC_LENGTH; }
if (!unlocked) { return NRC_SECURITY; }

Under 15.5, one result variable is set along the way and returned once. The rule is advisory, and many projects formally disapply it because the single-exit form can bury the main path in nesting. But many car makers' guidelines make it binding, so you must be able to write both. The idiom that keeps single-exit code flat is "continue only while still OK":

uint8_t nrc = NRC_NONE;
if (len != 3U) {
  nrc = NRC_LENGTH;
} else if (!unlocked) {
  nrc = NRC_SECURITY;
} else {
  /* the work */
}
return nrc;

Rule 15.6 (required): always braces, including for a single statement after if, else, for and while.

Rule 14.4 (required): conditions are essentially Boolean. if (flags & 0x01U) is a finding; if ((flags & 0x01U) != 0U) is not. So is while (count), and if (ptr).

Rules 16.1 to 16.7: a well-formed switch. Every clause ends in an unconditional break (16.3: no fall-through), there is always a default (16.4), which is first or last (16.5), and a switch has at least two clauses (16.6). A dispatch on a service identifier is a switch, so these govern the centre of a diagnostic server.

Rule 17.7 (required): the value returned by a non-void function shall be used. Ignoring NvM_WriteBlock's result is a finding, and usually a bug. Where the value really is not needed, an explicit (void) cast says so.

Rule 17.2 (required): no recursion, direct or indirect, because the stack depth must be boundable. Rule 21.3 (required): no dynamic memory, because exhaustion and fragmentation cannot be ruled out. Together they are why the worst-case stack and memory of an ECU can be calculated at all.

Rule 13.5 (required): no persistent side effects in the right-hand operand of && or ||. if ((len > 2U) && (read_byte() == 0x01U)) hides a call that happens only sometimes. Take the call out first.

Rule 8.7 (advisory) and 8.4 (required): what is used in one file is static; what is shared has a declaration in a header that the defining file includes.

Here is a small handler written to all of them. It runs; the checker that this site's problems use would pass it.

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

#define NRC_NONE      0x00U
#define NRC_LENGTH    0x13U
#define NRC_RANGE     0x31U
#define NRC_SECURITY  0x33U

static uint8_t lock_timeout_s = 30U;

/* WriteDataByIdentifier for one DID. One exit, braces everywhere, Boolean conditions, unsigned constants. */
static uint8_t write_lock_timeout(const uint8_t *request, uint16_t length, bool unlocked)
{
  uint8_t nrc = NRC_NONE;

  if (length != 4U) {
    nrc = NRC_LENGTH;
  } else if (!unlocked) {
    nrc = NRC_SECURITY;
  } else if ((request[3] < 5U) || (request[3] > 120U)) {
    nrc = NRC_RANGE;
  } else {
    lock_timeout_s = request[3];
  }

  return nrc;
}

int main(void)
{
  const uint8_t good[4] = { 0x2EU, 0x01U, 0x10U, 60U };
  const uint8_t high[4] = { 0x2EU, 0x01U, 0x10U, 200U };

  (void)printf("locked:   NRC 0x%02X\n", (unsigned int)write_lock_timeout(good, 4U, false));
  (void)printf("too high: NRC 0x%02X\n", (unsigned int)write_lock_timeout(high, 4U, true));
  (void)printf("short:    NRC 0x%02X\n", (unsigned int)write_lock_timeout(good, 3U, true));
  (void)printf("accepted: NRC 0x%02X, timeout now %u s\n", (unsigned int)write_lock_timeout(good, 4U, true), (unsigned int)lock_timeout_s);
  return 0;
}

Details to notice: (void)printf(...) because printf returns a value (17.7); each sub-expression of || in its own parentheses (12.1, advisory); the cast to unsigned int for %X and %u, since passing a uint8_t to a variadic function relies on promotion. On a real project printf itself would be a finding (21.6) in production code and permitted only in test code, which is one reason projects define different rule sets for the two.

Deviations

Embedded code cannot follow every rule. The textbook case is a memory-mapped register:

#define GPIOA_ODR (*(volatile uint32_t *)0x40020014U)

That converts an integer to a pointer, which Rule 11.4 (advisory) advises against and 11.6 restricts. There is no other way to reach hardware in C. The answer is a deviation: a documented, reviewed, approved decision not to follow a guideline in a stated set of circumstances. MISRA Compliance:2020, the companion document that defines what "compliant" means, sets what a deviation record must contain:

FieldFor the register example
The guidelineRule 11.4
The scoperegister access macros in the MCAL headers only
The reason, from the permitted set (code quality, access to hardware, integration of adopted code ...)access to hardware
The justification: why following the rule is not possible or not bestthe addresses are fixed by the device; the vendor's header is the only definition
The risk, and how it is controlledaddresses come from the vendor's device header; wrong addresses are caught by integration tests on the target
Approvalwho, when, with what authority

Three properties separate a deviation from an excuse:

  • It is specific. "Rule 11.4 is disabled" is not a deviation. "Rule 11.4 does not apply to the macros in regs.h" is. A deviation permit generalises a common case once, so that every use need only reference it.
  • The reason is technical, never convenience. "The code works", "there is no time" and "the tool is wrong" are not reasons. A false positive is a tool problem: it is recorded as such, with the analysis that shows the code is compliant, not as a deviation.
  • It is traceable in the code. A tool-specific comment or pragma at the site suppresses the finding and names the record: /* DEV-0012: Rule 11.4, access to hardware */.

A project may also recategorise guidelines in its guideline re-categorization plan: an advisory rule can be raised to required, or disapplied with a rationale. Mandatory guidelines cannot be lowered; required ones cannot be disapplied.

Claiming compliance

"The code is MISRA compliant" is a formal claim, and MISRA Compliance:2020 says what must stand behind it:

  • A guideline enforcement plan: for every guideline, how it is checked: which tool and which of its checks, or which review step for a directive no tool covers.
  • A guideline re-categorization plan: the project's category for every guideline.
  • The deviation records and permits, each approved.
  • A guideline compliance summary: for every guideline, one of compliant, deviations, violations (allowed only for advisory guidelines) or disapplied.
  • Evidence that the tools were configured as planned and run on the delivered code, with their versions.

For code you did not write, such as a vendor HAL, a generated RTE or a library, the same document defines adopted code: you are not expected to make it compliant, but its interface to your code must be, and its headers must not drag violations into your analysis.

Daily life with this process:

  • The analyser runs in continuous integration, and a new finding fails the build. A project that lets findings accumulate "to be fixed before release" never fixes them.
  • Suppressions are reviewed like code. A reviewer checks that the record exists and that the suppression covers one line, not a file.
  • Rules are chosen for both the project's own and its customer's rule sets: a car maker's coding guideline is typically MISRA plus a list of raised categories and house rules.
  • Commercial analysers used for safety work (Helix QAC, Polyspace, Coverity, LDRA, PC-lint Plus) come with a tool qualification kit, because ISO 26262 asks for confidence in the tools that provide evidence.

Interview question: What do mandatory, required and advisory mean in MISRA C, and what is a deviation?

Answer: They are the categories of guideline. A mandatory guideline must always be followed and cannot be deviated from. A required guideline must be followed unless a formal deviation has been raised and approved. An advisory guideline should be followed; not following it does not need a formal deviation, though it should be documented, and a project can raise it to required or disapply it. A deviation is a documented and approved decision not to follow a guideline in defined circumstances: it names the guideline and the exact scope, gives a permitted reason and a technical justification, describes the risk and how it is controlled, and is referenced from the code where the finding is suppressed.

Interview question: What is the difference between a decidable and an undecidable MISRA rule?

Answer: For a decidable rule a static analyser can always determine from the source whether the code complies, for example that every switch has a default or that a function has one exit. For an undecidable rule the answer can depend on values or paths known only at run time, for example that an object is never read before being set or that an array index stays in range, so no tool can be both complete and correct. Analysers report possible violations for such rules, with false positives and false negatives. A clean report for an undecidable rule is therefore supporting evidence, not proof, and is complemented by reviews, defensive code and testing.

Going deeper

Interview question: You join a project with 30,000 existing MISRA findings and a release in three months. What do you propose?

Answer: Stop the count growing first: baseline the current findings and make the build fail on any new one, so all new and changed code is clean. Then triage the baseline by risk rather than by count. Mandatory rules and those tied to undefined behaviour come first, such as uninitialised reads, out-of-bounds arithmetic, overflow and shifts, and they are fixed with review and tests because each may be a live bug. High-volume mechanical findings, such as unsigned suffixes or missing braces, are fixed file by file with tool support in commits that change nothing else, so that they are easy to review. Findings in vendor or generated code are handled as adopted code. Whatever remains at release is covered by deviations or recorded honestly in the compliance summary, with a dated plan.

Interview question: Why do safety standards ask for a language subset such as MISRA C at all?

Answer: C leaves a great deal undefined, unspecified or implementation-defined, and compilers are entitled to assume undefined behaviour never happens, so a program can pass its tests and still fail with another compiler version or optimisation level. A subset removes or controls the constructs where that happens, and those that are legal but commonly misread, such as implicit conversions, fall-through and side effects in conditions. It also makes code uniform enough for reviewers and tools to check, and bounds resources by banning recursion and dynamic memory. ISO 26262 part 6 lists the use of language subsets among its recommended design and coding principles for every integrity level for these reasons: it reduces systematic faults that testing alone would not reliably find.

Interview question: An analyser flags a line that you are sure complies with the rule. What do you do?

Answer: First doubt yourself: reread the rule's text, amplification and exceptions, and check the essential types involved, because most "false positives" are real findings read too quickly. If the code does comply, do not raise a deviation, since a deviation says the code violates the guideline. Record it as a tool false positive, with the analysis showing compliance, suppress it at that line with a reference to the record, and report it to the tool vendor. If the same pattern is flagged often, consider rewriting the code so the tool can follow it, which usually makes it clearer for people too, and review the suppression when the tool is upgraded.

Explain it: In your own words, explain why "we ran a MISRA checker and it reported nothing" is not the same as "the code is MISRA compliant".

Answer: A checker covers only the rules it implements and was configured to check, so the claim needs a plan showing how every guideline is enforced, including directives that need review rather than a tool. For undecidable rules a tool can miss real violations, and rules with system scope need whole-program analysis, not a per-file run. Suppressed findings must each be backed by an approved deviation with a scope and justification. Compliance is therefore a documented claim: the enforcement plan, the project's categories for each guideline, the deviation records, and a summary stating for each guideline whether the code is compliant, has deviations or is disapplied, tied to the tool versions and the delivered code.