Try Embedded

Undefined behaviour

Undefined, unspecified and implementation-defined behaviour, and why the optimiser makes UB dangerous.

What the C standard leaves open

The C standard does not define every program's behaviour. It sorts the gaps into three kinds, and interviewers expect you to know the difference:

KindMeaningExample
Implementation-definedEach compiler chooses and must document the choicesizeof(int), whether char is signed, right shift of a negative number
UnspecifiedSeveral outcomes are allowed; the compiler need not say which, and may differ each timeThe order in which function arguments are evaluated
UndefinedNo requirement at all: anything may happen, including "seems to work"Signed overflow, out-of-bounds access, null dereference

Implementation-defined and unspecified behaviour make code non-portable. Undefined behaviour (UB) makes it wrong, and the reason it matters so much is the optimiser.

Why "anything can happen" is literal

The compiler is allowed to assume your program never has undefined behaviour, and it uses that assumption to optimise. So code with UB is not just "wrong in the bad case": the optimiser can transform the correct-looking code around it.

int check_overflow(int x) {
  if (x + 1 < x)          // signed overflow is UB, so the compiler may assume this is never true
    return 1;             // ...and delete this branch entirely at -O2
  return 0;
}
void read_status(struct dev *d) {
  int flags = d->flags;   // dereference: the compiler now assumes d is not NULL
  if (d == NULL) return;  // ...so this check can be removed
  use(flags);
}

Both pass every test at -O0 and break at -O2. That is the signature of UB: behaviour that changes with optimisation level, compiler version, or an unrelated edit.

The undefined behaviour you will meet in firmware

The simulator in this course detects many of these and stops with an explanation, instead of silently corrupting memory as a real chip would. Each example below is meant to fail.

Reading an uninitialised variable

#include <stdio.h>

int main(void) {
  int total;                    // local variables start with whatever was on the stack
  for (int i = 0; i < 3; i++) total += i;
  printf("%d\n", total);
  return 0;
}

Globals and static variables are zero-initialised by the startup code; locals are not.

Going outside an array

#include <stdio.h>

int main(void) {
  int samples[4] = { 1, 2, 3, 4 };
  int sum = 0;
  for (int i = 0; i <= 4; i++) sum += samples[i];   // <= reads samples[4]
  printf("%d\n", sum);
  return 0;
}

On a microcontroller this reads whatever lies next in RAM, and a write would corrupt it: a different variable, a return address, the stack canary.

Using memory after its lifetime

#include <stdio.h>

static int *latest(void) {
  int value = 42;
  return &value;                // value dies when the function returns
}

int main(void) {
  int *p = latest();
  printf("%d\n", *p);
  return 0;
}

Shifting too far

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

int main(void) {
  uint32_t mask = 1u;
  int bit = 32;
  printf("0x%08X\n", mask << bit);   // shifting a 32-bit value by 32 or more is UB
  return 0;
}

On Arm the hardware happens to use only the bottom byte of the shift amount, so 1u << 32 gives 0; on x86 it uses the bottom 5 bits and gives 1. Neither is guaranteed, and the optimiser may assume it never happens.

Signed integer overflow

INT_MAX + 1 is undefined. Unsigned arithmetic is defined to wrap modulo 2^N, which is why timers, sequence numbers and checksums use unsigned types. The simulator wraps signed overflow like real hardware does rather than stopping, which is exactly why it is dangerous: it looks fine until the optimiser exploits it.

More to know by name

UBTypical firmware cause
Null pointer dereferenceUsing a driver handle before init succeeded
Strict aliasing violationReading a float through a uint32_t *; use memcpy or a union instead
Unaligned access through a cast pointerParsing a packet by casting uint8_t * to uint32_t *
Modifying a variable twice without a sequence pointi = i++ + 1;, a[i] = i++;
Modifying a string literalchar *s = "abc"; s[0] = 'x'; (it may be in flash)
Data raceA variable written by an interrupt and read by main without volatile and care
Division by zero, INT_MIN / -1Unchecked sensor values
Calling through a function pointer of the wrong typeCasting callbacks to make them "fit"

Defending against UB

  1. Compiler warnings: -Wall -Wextra -Werror, plus -Wshadow -Wconversion -Wcast-align -Wstrict-aliasing.
  2. Sanitizers on the host: compile unit tests with -fsanitize=undefined,address. UBSan reports overflow, bad shifts and misaligned accesses at the line they happen; ASan catches out-of-bounds and use-after-free.
  3. Static analysis: clang-tidy, cppcheck, and MISRA C checkers, whose rules exist largely to avoid UB.
  4. Defined alternatives: unsigned types for wrapping arithmetic, memcpy for type punning, explicit range checks before shifts and divisions.
  5. Know your target's flags. -fwrapv makes signed overflow wrap and -fno-strict-aliasing disables aliasing-based optimisation; the Linux kernel uses both. They make code more forgiving, not more portable.

Pitfall: "It works on my board" proves nothing about UB. The same source can break with the next compiler release, at a different optimisation level, or when a line is added nearby.

Interview question: What is the difference between undefined, unspecified and implementation-defined behaviour?

Answer: Implementation-defined behaviour is chosen by each compiler and documented, such as the size of int or the result of right-shifting a negative number. Unspecified behaviour allows several outcomes without the compiler having to say which, such as the order of evaluating function arguments. Undefined behaviour places no requirement on the program at all, such as signed overflow or an out-of-bounds access, and the optimiser may assume it never happens, which can change the meaning of surrounding code.

Interview question: A bug disappears when you compile at -O0 or add a printf. What do you suspect and how do you find it?

Answer: Undefined behaviour that the optimiser exploits, or a timing or memory-layout dependent bug such as an uninitialised variable, a buffer overflow or a race. Build the logic for the host with UBSan and ASan and run the tests, turn on all warnings, run static analysis, and check for missing volatile on shared variables. On the target, use a watchpoint on any variable that changes unexpectedly and check stack usage.

Build it: remove the undefined behaviour

This is step 2 of the module project. The ride statistics code passed every test on the developer's PC, then gave random numbers on the bike. Each function below contains a case of undefined behaviour: code that C does not define, so it may work, crash or lie. The simulated chip here catches them. Fix each function so it is defined for every input listed.

Lab: Fix four kinds of undefined behaviour

  • avg_speed(s, n) returns the average of n speed samples, or 0 when n is 0. (Bugs: the sum starts with no value, and n can be 0.)
  • best_of_last(s, n, k) returns the highest of the last k samples, or of all of them if k is larger than n, and 0 for no samples. (Bug: it reads before the start of the array.)
  • gear_bit(gear) returns a mask with bit gear set, for gears 0 to 31, and 0 for any other gear. (Bug: shifting by 32 or more is undefined.)
  • pace_s_per_km(speed_x10) returns seconds per kilometre, 36000 / speed_x10, or 0 when standing still. (Bug: division by zero.)

Going deeper

Interview question: How would you protect a car's speed sensor code from undefined behaviour?

Answer: Use unsigned or wider types where overflow is possible, check ranges before arithmetic, avoid out-of-bounds indexing and uninitialised variables, and compile with warnings as errors. Run static analysis and sanitizers (on a PC build), and test at the boundaries, because undefined behaviour often appears only at high optimisation.

Interview question: What is strict aliasing, and how do you read the bytes of a float safely?

Answer: The strict aliasing rule says an object may only be accessed through an lvalue of its own type (or a compatible type, or a character type). Reading a float through a uint32_t pointer violates it, and the optimiser may reorder or remove accesses assuming the two pointers cannot refer to the same object. Copy the bytes with memcpy into a uint32_t (compilers turn this into a single register move), or use a union, which C (unlike C++) permits for type punning. Accessing any object as unsigned char is always allowed.

Interview question: Is i = i++ + 1; undefined, and why?

Answer: Yes in C. Between two sequence points (C11 calls it "unsequenced") the object i is modified twice, once by the increment and once by the assignment, with no ordering between them, which is undefined behaviour. The fix is to write the intent as separate statements. Interviewers use it to check whether you know that "the compiler will do something sensible" is not a safe assumption.

Explain it: In your own words, explain why undefined behaviour can break code that is not itself on the buggy line.

Answer: The compiler optimises under the assumption that the program never executes undefined behaviour. When it sees an operation that would be undefined for some inputs, such as dereferencing a pointer or adding to a signed integer, it is entitled to conclude those inputs never occur, and then simplify other code using that conclusion: removing a null check that comes after a dereference, or deleting an overflow check that relies on signed wrap-around. So the visible failure can appear in a correct-looking check elsewhere, and it can change with the optimisation level or compiler version.