Skip to content
Tech Interview Prep
Technical interview guide

Embedded C/C++ & Memory Constraints

Why systems programming on bare metal with kilobytes of RAM surfaces correctness issues that rarely bite on a general-purpose OS.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: GCC current C/C++ implementation and optimization guidance; CMSIS 6 startup/linker/compiler control; Arm ABI and SEI CERT guidance reviewed 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Walk me through where .text, .rodata, .data, .bss, the stack and the heap live in an embedded image, which consume flash, which consume RAM, and what the startup code does to each before main() runs?

Answer

Assume a bare-metal Cortex-M with execute-in-place flash and SRAM, built with arm-none-eabi-gcc or Arm Compiler 6 plus a scatter file. The linker emits one load image in flash and a run image in RAM; they differ only where a section has a different load address (LMA) and virtual address (VMA).

sectionflash (LMA)RAM (VMA)startup action
.isr_vectoryes, at 0x08000000nonone
.textyesno (XIP)none
.rodatayesnonone
.datayes, initialiser imageyescopied flash to RAM
.bssno, size onlyyeszeroed
.noinitnoyesnone
stacknoyesnone; painted for watermark
heapnoyesnone; grown by _sbrk

So .text and .rodata cost flash only, .bss/.noinit/stack/heap cost RAM only, and .data is the only one that costs both: it is counted twice in the budget.

The startup code is what makes that true. GCC's Reset_Handler:

c extern uint32_t _sidata, _sdata, _edata, _sbss, _ebss; void Reset_Handler(void) { uint32_t *src = &_sidata, *dst = &_sdata; while (dst < &_edata) *dst++ = src++; / .data: LMA -> VMA */ for (dst = &_sbss; dst < &_ebss; ) dst++ = 0; / .bss / SystemInit(); __libc_init_array(); / C++ ctors */ main(); }

_sidata is the flash load address the linker script assigns to .data; _sdata/_edata bracket the RAM copy. Arm Compiler does the same work inside __main, driven by the scatter file's RW_IRAM1 region. .bss has no flash image at all: only its size is recorded, which is why a 40 KB .bss costs zero flash.

Arithmetic on an STM32F103C8 (64 KB flash, 20 KB SRAM), hypothetical but representative: .text 18.0 KB, .rodata 3.0 KB, .data 1.2 KB, .bss 6.0 KB, .noinit 0.5 KB, stack 2.0 KB, heap 1.0 KB. Flash = 18.0 + 3.0 + 1.2 = 22.2 KB. RAM = 1.2 + 6.0 + 0.5 + 2.0 + 1.0 = 10.7 KB.

arm-none-eabi-size prints text data bss dec; the data column is the flash cost of .data, not its RAM cost, and dec is not RAM usage. Reading it as RAM is the classic budget error.

Failure modes worth naming:

  • A bootloader that jumps to the application's main, or a warm path that re-enters after its own startup, skips the copy: .data holds whatever was in RAM. Detect with a canary word in .data checked at the top of main, or a CRC over [_sdata, _edata).
  • The linker script gives .data an LMA that overlaps .text or the vector table. size will not show it; the .map file's load addresses will.
  • Stack grows down into .bss or the heap. Guard with an MPU region below the stack, or have _sbrk fail when the new break would cross __StackLimit.
  • A variable written = 0 lands in .bss under GCC's default -fzero-initialized-in-bss, so anything that must be non-zero at first read is silently zero.
  • -ffunction-sections -fdata-sections plus --gc-sections is what keeps unused code out of .text; without it, dead drivers inflate flash and push the .data image around.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

What does it mean to compile for a freestanding environment rather than a hosted one, and which parts of the C/C++ runtime must the firmware supply itself?

Answer

Hosted versus freestanding is a property of the translation environment, not of the chip. C11 §5.1.2.1 defines a hosted implementation: the whole standard library is available, and startup is the C runtime calling main and then handling exit. §5.1.2.2 defines freestanding: only a small header set is required, and startup need not be main at all. GCC selects the second with -ffreestanding, which also implies -fno-builtin, so GCC stops assuming the standard semantics of memcpy, memset and printf.

What freestanding guarantees is nine headers: <float.h>, <iso646.h>, <limits.h>, <stdalign.h>, <stdarg.h>, <stdbool.h>, <stddef.h>, <stdint.h>, <stdnoreturn.h>. C23 adds <stdbit.h> and <stdckdint.h>. That is the whole list. stdio, stdlib, string, time and the C++ library are not there; if you want them you link a libc built for the target (newlib, newlib-nano, picolibc) and accept its syscall stubs.

hostedfreestanding
entryCRT _start → __libc_start_main → mainyour Reset_Handler / _start
headersall of the standard librarythe nine above
main returnsexit() runs atexit handlers, flushes stdionothing to return to
builtinsGCC assumes standard semantics-ffreestanding implies -fno-builtin
memory initkernel maps .data/.bssyour startup copies .data and zeroes .bss

So the firmware supplies what the hosted CRT would have supplied:

  • Startup and vector table. The CMSIS startup file is exactly this: vector table, Reset_Handler, and a call into SystemInit before main.
  • A linker script or scatter-loading file. It defines load and execution regions, the .data load address, .bss extent, and the heap and stack symbols. Without it the linker places sections at addresses that do not exist on the part.
  • memcpy, memset, memmove, memcmp. GCC emits calls to these for struct assignment and aggregate initialization even under -ffreestanding, so they must exist. Define them in a file compiled with -fno-builtin, or GCC may recognise your memcpy body and replace it with a call to memcpy: infinite recursion on the first struct copy.
  • malloc backing. newlib's malloc calls _sbrk; you supply it over a fixed arena, or you supply no malloc at all and the link fails loudly.
  • C++ static initialization. Constructors live in .init_array and run only if you call __libc_init_array (or the Arm equivalent) between .bss zeroing and main. Skip it and every global with a non-trivial constructor reads as zero.
  • Exception and RTTI runtime. -fno-exceptions -fno-rtti is the usual firmware answer; keeping them pulls in __cxa_throw, unwind tables and libsupc++.
  • Compiler helpers. -nostdlib drops libgcc, so 64-bit division on a Cortex-M0 has no __aeabi_uldivmod; add -lgcc back explicitly. -fstack-protector needs __stack_chk_fail and __stack_chk_guard.

Detection is cheap: arm-none-eabi-nm -u firmware.elf lists every undefined symbol, and -Wl,--no-undefined turns them into link errors instead of a stub that returns garbage. -Wl,-Map=out.map shows which object pulled in printf.

Failure modes worth naming: a missing memcpy shows up as a link error or, worse, a weak stub; constructors never running shows up as a global that should read 3 reading 0; accidental semihosting shows up as a hang the moment the debugger detaches (look for BKPT 0xAB in the disassembly); main returning with no _exit loops or resets, so decide which and make the watchdog agree.

Freestanding is the wrong choice when there is an OS underneath (Linux, Zephyr, FreeRTOS with a full BSP) because you then pay for a startup and linker script you did not need. Even there you still own the linker script and the vector table; what you stop owning is memcpy and malloc.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

The link fails with "region FLASH overflowed by 12 KB". Walk me through how you use the linker map to find what is consuming the space, and what you would cut.

Answer

The map file is the linker's own accounting of where every input section landed. It is the only build artefact that ties a byte count back to a specific object file and symbol, which is why it is the first thing to open when a region overflows.

Build it so it can answer the question. -Wl,-Map=build/fw.map,--cref writes the map; -Wl,--print-memory-usage prints just the region summary to stdout. Attribution only works if you also compile with -ffunction-sections -fdata-sections, so each function and each data object gets its own section. Without those flags the map stops at the translation unit and you can only say "protocol.o is large", never "parse_frame is large".

Three passes. The top has Memory Configuration: each region's origin and length. Below it, every output section (.text, .rodata, .data, .bss) with its address, size and region. Then the input-section lines, one per object, in the form build/protocol.o(.text.parse_frame). The bottom is the symbol table sorted by address, which is where a large const table shows up by name.

Excerpt from a map:

Memory Configuration Name Origin Length Attributes FLASH 0x08000000 0x00040000 xr RAM 0x20000000 0x00020000 rw

.text 0x08000000 0x3f8c0 .text.main 0x08000a1c 0x1c4 build/main.o .text.parse_frame 0x08001b40 0x2a80 build/protocol.o .rodata.lut 0x0802c000 0x8000 build/tables.o

Arithmetic: FLASH is 0x40000 = 262144 bytes, .text is 0x3f8c0 = 260288, so headroom is 1856 bytes. A 12 KB feature overflows by 12288 − 1856 = 10432 bytes. tables.o's .rodata.lut is 0x8000 = 32768 bytes, 12.5% of flash; parse_frame alone is 0x2a80 = 10880 bytes. Those two are the first candidates, and the map names them, which is the whole point.

map evidencediagnosisaction
one .text.fn dominatesa single function, often a switch jump table or an inlined helper-Os, split the function, check for accidental inlining
.rodata.* in tables.oconst lookup tablemove to external flash, compress, or compute at runtime
many small .text.* with no callerdead code retained-ffunction-sections -fdata-sections plus -Wl,--gc-sections
.data size counted in RAM but load address in FLASHinitialised data charged twicesee object sections; audit both load and run sizes

Cross-check with arm-none-eabi-nm --size-sort -S fw.elf, which sorts symbols by size without parsing the map.

Failure modes. A stale map: an incremental build that did not relink, or two build directories. Compare the map's mtime against the .elf. No -ffunction-sections: attribution lands on the wrong file and you trim the wrong thing. section .ccmram will not fit in region RAM is a different error from region RAM overflowed: the first is one section larger than the region, or pushed past its end by alignment; trimming other objects will not fix it. --gc-sections deleting an interrupt handler reachable only from the vector table: the map shows the symbol gone and the device hard-faults on the first interrupt, so the handler needs KEEP() in the linker script. With -flto the map names LTO-generated objects, not your source files; you need the LTO report or -ffat-lto-objects to attribute. And the map covers the load image only: stack and heap are not in it, so a map that fits says nothing about runtime RAM.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Walk me through how you read a linker map file to confirm that .data and .bss landed in the intended RAM region, code and constants in the intended flash region, and that no unexpected object was pulled in, and what you change when the map disagrees with the intended memory layout?

Answer

Assume GNU ld or the Arm linker, map generated with -Wl,-Map=build.map. The map is the linker's report of what it actually did, not what you intended. I read it in three passes.

Pass 1: regions. The Memory Configuration block lists each region with its origin and length, e.g. FLASH 0x08000000/0x40000, RAM 0x20000000/0x8000. That is the budget everything else is checked against.

Pass 2: section placement. For each output section the map lists the input sections and the resulting address range. .text and .rodata must sit inside FLASH; .data and .bss inside RAM. .data shows two addresses: the load address (LMA) in flash and the virtual address (VMA) in RAM. The startup code copies LMA→VMA before main. _sdata/_edata bracket the .data VMA range and _sbss/_ebss bracket .bss: those symbols mark section boundaries, not region boundaries. To check the region actually fits, compare the end of .bss (_ebss) against ORIGIN+LENGTH of RAM.

Pass 3: what got pulled in. Under each output section the map lists the archive members and object files that contributed. A call to printf drags in a large slice of libc. Build with -ffunction-sections -fdata-sections and link with --gc-sections; --print-gc-sections lists what was dropped, and nm -u or --trace-symbol finds the reference that kept something alive.

Worked example. RAM region 0x20000000/0x8000 (32 KB). Map summary:

sectionVMAsizeregion
.text0x08000000–0x0801C400112 KBFLASH
.rodata0x0801C400–0x0802400031 KBFLASH
.data0x20000000–0x2000280010 KBRAM
.bss0x20002800–0x2000900026 KBRAM

RAM used is 10 + 26 = 36 KB against a 32 KB region. Two findings. First, a 6 KB lookup table sits in .data because it was declared without const; it belongs in flash. Adding const moves it to .rodata, so .data becomes 4 KB and RAM used drops to 30 KB: inside the region. Flash grows by 6 KB, still far under 256 KB. Second, printf appears as a libc archive member under .text; replacing it with a small integer formatter removes it.

When the map disagrees, the change is one of three: the linker script (region sizes, a missing >REGION on a section, a new region), the code (add const, shrink a buffer, __attribute__((section(".name"))) to place explicitly), or the build flags (garbage collection, drop a library, switch to newlib-nano).

Failure modes worth naming: forgetting that .data's LMA is in flash and its VMA in RAM, so a missing startup copy leaves garbage in RAM; alignment padding opening gaps between sections; a weak symbol pulling in a default implementation; a section placed without >REGION landing at the default location; and .bss growing silently because a large array was zero-initialised instead of made const.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

How do you ensure ABI and toolchain compatibility when linking objects or libraries built by different compilers, compiler versions, or optimisation settings, and what can break?

Answer

Clarify first. "Different" splits three ways, and they fail differently: different vendor (GCC vs Clang vs MSVC), different version of the same vendor, or the same compiler with different flags. The first two usually surface as link errors. The third is the one that silently corrupts memory, because the linker has no idea a flag changed a struct layout.

The contract. An ABI fixes the calling convention (which registers carry arguments, who pops the stack, how floats are passed), data layout (struct padding, alignment, bit-field order, enum width), name mangling, the exception/unwinding model, RTTI and vtable layout, and the runtime library interfaces (libc, libgcc_s, libstdc++/libc++).

Core answer. Pin one toolchain per build, treat ABI-affecting flags as part of the interface, and verify at build time rather than run time.

  • Same compiler and version for every object. GCC's LTO is the sharp edge: -flto objects are GIMPLE bytecode, and GCC refuses to link LTO objects from a different major version. You get bytecode stream: version mismatch at link.
  • Match ABI-affecting flags across all translation units: -fshort-enums, -fpack-struct, -mstructure-size-boundary, -mabi=, -mfloat-abi=, -D_GLIBCXX_USE_CXX11_ABI=, -fno-exceptions, -fno-rtti. -O0 vs -O3 does not change the ABI; it only exposes latent undefined behaviour.
  • C++ standard library: GCC 5.1 switched std::string and std::list to the C++11 layout. _GLIBCXX_USE_CXX11_ABI=0 vs =1 changes mangled names (_ZNSs... vs _ZNSt7__cxx1112basic_string...), so it usually fails at link, but a std::string passed by value across a mismatched boundary is a real corruption path.

What breaks, with a trace. Take:

C
enum color { RED, GREEN, BLUE };   /* 0, 1, 2 */
struct pixel { enum color c; uint8_t v; };

Default x86-64: enum color's underlying type is int (4 bytes). c sits at offset 0, v at offset 4, struct alignment 4, so sizeof(struct pixel) == 8.

With -fshort-enums: the underlying type becomes the smallest that holds 0..2, i.e. unsigned char. c at offset 0, v at offset 1, alignment 1, so sizeof == 2.

Now link a caller compiled without the flag against a callee compiled with it. pixel[1] is at offset 8 for the caller and offset 2 for the callee. The caller reads the wrong bytes; if the caller allocates n * 2 and the callee writes n * 8, you get a heap overflow. No linker diagnostic.

Verification.

BreakDetect
Calling conventionobjdump -d, compare prologue/epilogue and which registers carry args; on ARM check VFP vs core registers
Struct layoutstatic_assert(sizeof(...) == N) and offsetof in a shared header; pahole on the DWARF
Name manglingnm -C --defined-only lib.a against the undefined symbols in the consumer
Runtime libsreadelf -d for NEEDED, ldd, and check versioned symbols (GLIBC_2.34)
C++ ABI driftabidiff old.so new.so (libabigail) or abi-compliance-checker

-Wabi (GCC) catches some C++ mismatches, and -Wl,-Map=out.map shows which object supplied each symbol.

When you can't rebuild. For a binary-only blob, abidiff and abi-compliance-checker compare exported ABI against a reference, but they only see what's in the symbol table and DWARF: they won't catch a flag that changed a struct the library never exposes in debug info. If the vendor won't tell you the compiler and flags, you're guessing. The safe move is to rebuild from source, or isolate the blob behind a C boundary with a hand-checked struct.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Design and validate embedded C/C++ firmware for allocation size.

Answer

Assumptions. 32-bit MCU, size_t is 32 bits, sizes arrive from a wire length field or a sensor count, the heap is a fixed pool, and the libc is newlib-nano or a vendor variant where calloc's overflow check is not guaranteed. If element size is a compile-time constant, most of this folds away at -O2.

Core. Never compute count * elem_size and hand the result to malloc. Do the multiply in a form that cannot wrap, and reject before allocating.

C
#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>

/* 0 = ok, -1 = overflow, -2 = zero, -3 = OOM */
int alloc_elems(void **out, size_t count, size_t elem_size) {
    if (count == 0 || elem_size == 0) return -2;
    size_t bytes;
    if (__builtin_mul_overflow(count, elem_size, &bytes)) return -1;
    void *p = malloc(bytes);
    if (!p) return -3;
    *out = p;
    return 0;
}

__builtin_mul_overflow is GCC/Clang; C23 spells it ckd_mul in <stdckdint.h>. The portable fallback is the division check from CERT INT30-C: if (count > SIZE_MAX / elem_size) return -1;.

Trace. 32-bit size_t, count = 0x40000001 (1,073,741,825), elem_size = 4.

stepvalue
true product count * 40x1_0000_0004
truncated to 32 bits0x0000_0004 = 4
malloc(4)succeeds
loop writes count elements~4 GiB past a 4-byte buffer
SIZE_MAX / 40x3FFF_FFFF = 1,073,741,823
count > that?yes → rejected

The division check and the builtin both reject it; the raw multiply does not.

Trade-offs. The division check costs a divide. With a constant elem_size the compiler folds SIZE_MAX / elem_size into an immediate: free. With a runtime element size, Cortex-M3/M4 SDIV is 2–12 cycles; M0 has no divide instruction and the software routine runs ~20–40 cycles. __builtin_mul_overflow is a multiply plus a flag test on M3/M4, so prefer it when element size is runtime and the core lacks hardware divide. Don't lean on calloc: C11 7.22.3.2 requires it to fail on overflow, but newlib-nano and several vendor libcs don't implement that, so on embedded you check yourself.

Failure modes and how you catch them.

  • Wraparound → undersized buffer, then out-of-bounds write. Catch with an MPU guard region or heap canary around the block, plus a debug assert bytes >= count * elem_size computed in 64-bit math.
  • Narrowing before the multiply: a 32-bit wire length cast to uint16_t first. Catch at parse time by rejecting any field value that doesn't fit its declared width.
  • Truncated transport: header declares 1000 bytes, 200 arrived. Catch by comparing declared length to bytes actually received before allocating.
  • Zero: malloc(0) returns NULL on some libc and a unique pointer on others; treat zero as an explicit branch, not an OOM.
  • Alignment: malloc is aligned for any type, but a flexible array member after a header needs sizeof(struct) (which already includes trailing padding) plus n * sizeof(elem); if you carve buffers yourself, pin it with _Static_assert(_Alignof(...)).

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Design and validate embedded C/C++ firmware for heap policy.

Answer

Core answer. Assume a single-core Cortex-M with no MMU, C11 or C++17, and a hard real-time loop where the worst-case allocation latency must be bounded. My default is: no general-purpose malloc/free in the steady-state path. Static storage for anything whose lifetime is the program's; a fixed-size pool for objects with dynamic lifetime; a bump arena for phase-scoped work; and a bounded allocator only where a library forces it. The deciding criterion is not "which is fastest" but "what is the worst-case latency and the peak footprint, and what happens when it fails."

optionalloc costpeak RAMfragmentationfailure path
static0 cyclessum of all objectsnonenone: link-time error
arena (bump)~5–10 cyclessum of live objects in phasenone within phasereturns NULL at cap
fixed pool~20–50 cyclesblocks × block sizebounded by block roundingreturns NULL when pool empty
newlib malloc100s–1000s cycles worst caseunboundedunboundedNULL, often ignored

Mechanism. An arena is a pointer bump: allocation is used += n after alignment, and free is used = 0 at phase end. O(1), no metadata, no fragmentation, but peak usage equals the sum of everything live at once. A fixed pool keeps a free-list of equal blocks: alloc pops, free pushes, so latency is constant and fragmentation is capped at the rounding waste per block. malloc walks bins and may coalesce or split, so its worst case depends on the heap's history: that history dependence is exactly what breaks a deadline.

C
// C11, checked with arm-none-eabi-gcc 13.2
typedef struct { uint8_t *base; size_t cap, used; } arena_t;

static inline void *arena_alloc(arena_t *a, size_t n, size_t align) {
    size_t off = (a->used + (align - 1)) & ~(align - 1);
    if (off + n > a->cap) return NULL;   // caller MUST handle
    a->used = off + n;
    return a->base + off;
}
static inline void arena_reset(arena_t *a) { a->used = 0; }

Trace with cap = 4096, used = 0: arena_alloc(24, 8) → off = 0, used = 24. arena_alloc(100, 8) → off = 24, used = 124. arena_alloc(4000, 8) → off = 124, 124 + 4000 = 4124 > 4096 → returns NULL. So a 4 KB arena cannot hold a 24 B, a 100 B and a 4000 B object simultaneously; an 8 × 512 B pool (4096 B) fits the first two but not the third. That arithmetic is the design decision.

Failure modes and detection.

  • Allocation failure ignored: NULL deref → HardFault. Detect by wrapping the allocator to count NULL returns and asserting in debug; MISRA-C 2012 Rule 21.3 forbids the unchecked case.
  • Hidden library allocation: printf, std::string, std::function, std::shared_ptr control blocks, exceptions. Detect by linking -Wl,--wrap=malloc and counting calls, and building -fno-exceptions -fno-rtti.
  • Pool ABA: a lock-free free-list where a node is freed and reallocated between a reader's load and its CAS. Detect with tagged pointers or hazard pointers, and stress under ThreadSanitizer.
  • Fragmentation soak absent: run a 72-hour soak with the worst-case alloc pattern and track the high-water mark via xPortGetMinimumEverFreeHeapSize() (FreeRTOS heap_4) or mallinfo2().
  • Reset leaks retained state: a watchdog reset does not clear the heap or pools. Read the reset-cause register (e.g. RCC_CSR on STM32) and re-init pools in startup.

Validation. Static analysis (MISRA, -fanalyzer) plus a -Wl,-Map check that .bss and heap sizes match the budget; runtime high-water counters and canaries; and fault injection that fails the Nth allocation to prove graceful degradation. Measure worst-case allocation latency with the DWT cycle counter, not by reasoning.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design and validate embedded C/C++ firmware for stack budget.

Answer

The 90-second answer

Pin down four things first, because the budget changes with each: does the RTOS run ISRs on the task stack or a separate main stack, is the FPU context live, is there any recursion or indirect call through a function pointer, and how much headroom the safety case demands. On a FreeRTOS Cortex-M port the first answer is "separate": tasks run on PSP, every ISR runs on MSP, so ISR nesting is a second budget, not part of the task's.

The budget is then: worst-case call path from static analysis, plus the exception frames for the deepest preemption chain, plus margin. Validate it with a runtime watermark under a test that deliberately nests interrupts, and guard the safety-critical task with an MPU region so the first write past the boundary faults instead of silently corrupting the neighbour.

Mechanism

Static side: compile with -fstack-usage (GCC/Clang) and read the .su files. One frame size per function. -fcallgraph-info=su emits a call graph annotated with those sizes so you find the worst path instead of guessing. -Wstack-usage=256 turns any frame over 256 bytes into a build error. This is exact for direct calls and blind to everything else: an indirect call through a function pointer has no edge in the graph, recursion has no bound, and library code compiled without the flag contributes nothing.

Runtime side: paint the stack with a known pattern at startup and scan for the deepest untouched word. FreeRTOS does this for you: tskSTACK_FILL_BYTE is 0xa5 and uxTaskGetStackHighWaterMark() returns the minimum free stack in words.

C
/* GCC 12.2 arm-none-eabi, Cortex-M4F, FreeRTOS 10.5.1 */
#define STACK_FILL 0xA5A5A5A5u

/* bytes of the region never touched since paint; 0 means it overflowed */
static size_t stack_unused(const uint32_t *base, size_t words) {
    size_t i = 0;
    while (i < words && base[i] == STACK_FILL) i++;
    return i * sizeof(uint32_t);
}

Trace with words = 8 and the top three words overwritten: base[0] through base[4] still hold 0xA5A5A5A5, base[5] does not. The loop advances i to 5 and exits, returning 20: 20 bytes untouched, 12 used. Correct.

Worked budget (hypothetical but representative: STM32F407, GCC 12.2 -O2). The .su files give control_task 48, pid_update 72, arm_mat_mult_f32 120, memcpy 24: a 264-byte worst path, rounded to a 512-byte task stack. On the MSP side ADC_IRQHandler is 40 bytes and can be preempted by TIM_IRQHandler at 32; with FP active that is 40 + 32 + 2×104 = 280 bytes, so 1 KB of MSP leaves room for a third level. Rule of thumb: require the watermark to stay under 70% of the allocation after the worst-case test.

Why ISR nesting multiplies

Each preemption pushes a fresh exception frame. On Cortex-M4F with FP context active that frame is 26 words = 104 bytes; without FP it is 8 words = 32 bytes. Lazy stacking (FPCCR.LSPEN) defers writing S0–S15 but still reserves the space, so the 104 bytes are consumed either way. Two nested handlers therefore cost 208 bytes of frame plus both handler frames. Worst-case depth is the number of priority levels that can preempt each other, not the number of interrupts.

Trade-offs

methodcatchesblind tocost
-fstack-usage + callgraphexact direct-call frames, at build timeindirect calls, recursion, un-instrumented libsfree, but overestimates when -foptimize-sibling-calls turns tail recursion into a loop
watermark scanreal usage on exercised pathspaths the test never runsone scan, no runtime cost
MPU guard regionthe first write past the boundary, immediatelynothing after the faultone MPU region; stack must be power-of-two aligned, 32 bytes minimum

Use static analysis to set the number, the watermark to prove it, and the MPU for the task whose overflow would take down the system.

Failure modes and how you see them

  • Indirect call missing from the callgraph → static undercounts. Symptom: watermark far above the static sum. Detect by diffing the two.
  • printf/vfprintf with %f in newlib can eat over a kilobyte. Detect with .su on the library, or a watermark jump the first time a log line fires.
  • Canary checked too late: FreeRTOS configCHECK_FOR_STACK_OVERFLOW == 1 only checks at a context switch, so an overflow that corrupts a neighbour between switches is found after the damage. Method 2 checks the last 16 bytes at the switch: still post-hoc. The MPU guard is the only one that faults at the write.
  • Tail calls: at -O2 GCC enables -foptimize-sibling-calls, so a function that looks recursive in source is a loop in the binary. Compare .su across -O0 and -O2 before trusting either.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Design and validate embedded C/C++ firmware for stack overflow.

Answer

Assume Cortex-M (M3/M4/M7), FreeRTOS 10.5, arm-none-eabi-gcc 12.2. The question splits in two: design makes overflow detectable and survivable, validate proves the detector actually fires. They need different answers.

Two stacks, two failure modes. Thread mode runs on PSP: one stack per task. Handler mode runs on MSP: every ISR shares it. On exception entry the hardware pushes an 8-word frame (R0–R3, R12, LR, PC, xPSR = 32 bytes) onto whichever stack was in use, then switches to MSP. A task that overflows wrecks its own stack but the fault handler still has MSP. An ISR that overflows MSP has nowhere to run.

Size from measurement, not guess. Run the worst-case path, read uxTaskGetStackHighWaterMark() (minimum free stack in words, not bytes: a classic bug is passing 512 to xTaskCreate expecting bytes and getting 2 KB). Add 64 bytes of preemption headroom: 32 for the hardware frame plus 32 for the R4–R11 that PendSV saves. A worst case measuring 700 bytes becomes 700 + 64 = 764, rounded to 1 KB.

Guard the bottom. Put a 32-byte no-access MPU region at the stack's lowest address. Any write past the limit raises MemManage with DACCVIOL (CFSR bit 1) immediately, not at the next context switch.

C
/* Cortex-M7, arm-none-eabi-gcc 12.2, FreeRTOS 10.5 */
static void guard_region(void *stack_bottom)
{
    MPU->RNR  = 0;
    MPU->RBAR = ((uint32_t)stack_bottom & MPU_RBAR_ADDR_Msk)
              | MPU_RBAR_VALID_Msk;
    MPU->RASR = (0u << MPU_RASR_AP_Pos)      /* AP=000: no access */
              | (4u << MPU_RASR_SIZE_Pos)    /* 2^(4+1) = 32 B */
              | MPU_RASR_ENABLE_Msk;
    MPU->CTRL = MPU_CTRL_PRIVDEFENA_Msk | MPU_CTRL_ENABLE_Msk;
    __DSB(); __ISB();
}

Enable the specific faults first: MemManage, BusFault and UsageFault are off by default and escalate to HardFault, which loses the cause: SCB->SHCSR |= SCB_SHCSR_MEMFAULTENA_Msk | SCB_SHCSR_BUSFAULTENA_Msk | SCB_SHCSR_USGFAULTENA_Msk;

Record, then reset. Keep the record in .noinit so the C runtime doesn't zero it, and write a magic value so boot can tell a real crash from cold RAM.

C
__attribute__((section(".noinit"))) static crash_t g_crash;

void MemManage_Handler(void)
{
    uint32_t *frame = (uint32_t *)__get_PSP();  /* thread-mode frame */
    g_crash.cfsr  = SCB->CFSR;                  /* DACCVIOL = bit 1 */
    g_crash.pc    = frame[6];                   /* stacked PC */
    g_crash.magic = 0xC0FFEE01;
    NVIC_SystemReset();
}

If the fault came from an ISR, PSP is not the faulting stack: check SCB->CFSR for MSTKERR/MUNSTKERR before trusting the frame.

Validate by injecting the fault. A test task that recurses until the guard trips, run in CI. Assert: MemManage fires, g_crash.cfsr & (1<<1) is set, the record survives reset, boot_count increments, and after three resets the system enters safe mode instead of looping. Static side: -fstack-usage emits a .su file per object; sum the call graph (puncover does this) and gate the build with -Wstack-usage=1024. Runtime side: soak test, then assert uxTaskGetStackHighWaterMark() stays above 64 bytes on every task.

Failure modes and how you catch them.

failuredetection
Recursive logger in the handlerprintf needs ~600 B–1 KB on the already-exhausted MSP → double fault → lockup. Keep the handler async-signal-safe: raw bytes to a UART FIFO.
printf's own framenewlib vfprintf with %f is the worst offender. Read its .su file; use newlib-nano or a fixed-point formatter.
Corrupted return addressOverflow overwrites the stacked PC, so the fault is a HardFault from an invalid fetch and the PC is garbage. If CFSR has no MemManage bit, treat the PC as suspect.
Handler on the same stackOverflow inside an ISR leaves MSP exhausted. Limit ISR nesting with BASEPRI masking and check MSP high-water in the startup file.
Crash record overwritten at bootStartup zeroes .bss. Put the record in .noinit, verify the linker script, and check the magic value.

Trade-offs. MPU guard catches the write immediately but costs one of 8 (M3/M4) or 16 (M7) regions per task. FreeRTOS configCHECK_FOR_STACK_OVERFLOW=2 fills the stack with 0xA5A5A5A5 and checks the low 16 bytes each context switch: cheap, but only detects overflow that already happened. High-water marks cost nothing but only cover paths you ran. -fstack-usage covers paths you didn't, but misses indirect calls and recursion. Use all four; none alone is sufficient.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design and validate embedded C/C++ firmware for fixed-width types.

Answer

First 90 seconds

I'd pin the toolchain before answering: C11 or C++17, GCC or Clang, 32-bit little-endian ARM. "Fixed-width" means the <stdint.h> types (uint8_t, int32_t, uint64_t) which the standard guarantees are exactly that many bits with no padding bits, and since C23 (C++20) the signed ones are two's complement. My rule: fixed-width types at every boundary (wire format, memory-mapped register, shared memory, on-disk record) and native int or size_t for locals and loop counters that never cross a boundary.

That split is the trade-off. MISRA C:2012 Directive 4.6 (advisory) pushes typedefs in place of basic numerical types, and teams read it as "everywhere". Applied literally it hurts: uint32_t i for a loop counter forces a zero-extend on every increment on some targets and hides that the value is a small index. size_t is the right type for sizes and ptrdiff_t for pointer differences: those are the standard's own width-carrying types. Use uint32_t where the width is part of the contract; use int where it isn't.

Design

For a wire header (1 byte type, 4 bytes big-endian length) I never cast a buffer pointer to a struct. Padding and alignment make that wrong, and unaligned uint32_t loads fault on some ARM cores.

C
#include <stdint.h>
#include <string.h>

_Static_assert(sizeof(uint32_t) == 4, "no 32-bit type");

static uint32_t read_be32(const uint8_t *p) {
    uint32_t v;
    memcpy(&v, p, sizeof v);       /* no alignment assumption */
    return __builtin_bswap32(v);   /* host is little-endian */
}

Trace: p = {0x00, 0x00, 0x01, 0x00}. memcpy fills v with the little-endian interpretation, 0x00010000. __builtin_bswap32 reverses the bytes to 0x00000100 = 256. That is the wire value.

Failure modes and how I catch them

  1. Raw struct copy. struct { uint8_t type; uint32_t len; } is 8 bytes, not 5: three padding bytes after type. Detection: _Static_assert(sizeof(struct hdr) == 5, ...) fails the build. Cost if missed: the peer reads the length from the wrong offset and the protocol desynchronizes.

  2. Signed overflow. int32_t a = INT32_MAX; a + 1; is undefined behaviour, not wrap. Detection: build with -fsanitize=signed-integer-overflow,undefined and run the unit tests; use uint32_t for counters meant to wrap.

  3. Atomicity assumed. A uint32_t load is one instruction on Cortex-M but four on an 8-bit AVR, so an ISR can tear it. Detection: _Static_assert(__atomic_always_lock_free(4, 0), "uint32_t not lock-free here");, if it fails, use atomic_uint_least32_t or mask interrupts.

  4. printf format. uint32_t is unsigned int on ILP32 but unsigned long on LP64. Detection: include <inttypes.h> and use PRIu32; -Wformat catches the mismatch at compile time.

  5. Endianness. The same memcpy on a big-endian target returns the wrong value. Detection: a golden-vector unit test with a known byte pattern, run in CI on both endiannesses (QEMU covers big-endian MIPS/PowerPC).

Validation

Static asserts for sizes and lock-freedom, UBSan/ASan in the test build, byte-level golden vectors for every wire field, and -Wconversion -Wsign-conversion to catch implicit narrowing. That set catches all five above before hardware.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

Design and validate embedded C/C++ firmware for integer promotions.

Answer

Pin the target first: on a 32-bit Cortex-M with GCC 12 or Clang 16, int is 32 bits, so every type narrower than int (uint8_t, int8_t, uint16_t) promotes to signed int before any arithmetic or bitwise op. On a 16-bit-int part like MSP430 or AVR, uint16_t promotes to unsigned int instead, so identical source behaves differently. State the target before reviewing.

The rule is C11 6.3.1.1p2: if int can represent all values of the original type, the value converts to int; otherwise to unsigned int. So uint8_t/uint16_t become int; uint32_t stays unsigned int.

Trace 1: silent truncation through a shift.

C
uint8_t x = 1;
x = x << 7;   // x -> int, 1<<7 = 128, back to uint8_t = 128
x = x << 1;   // x -> int, 128<<1 = 256, back to uint8_t = 0

x ends at 0. No UB, conversion back to unsigned is modulo 256, but the data is gone. -Wconversion flags the narrowing assignment.

Trace 2: signed/unsigned comparison silently skips the guard.

C
int len = -1;
if (len < sizeof(buf)) {        // sizeof(buf) is size_t (unsigned); len -> 0xFFFFFFFF
    memcpy(dst, src, len);      // never reached
}

With a 16-byte buffer, len converts to 0xFFFFFFFF, and 4294967295 < 16 is false, so the body never runs. The copy is silently skipped and dst keeps whatever it held. The direction of the comparison decides the outcome: flip the guard to if (len > sizeof(buf)) return -EINVAL; and the same -1 converts to 0xFFFFFFFF > 16, which is true, so the error path fires and the negative length is caught. Same promotion, opposite result, which is why you read the comparison, not just the types. Fix: test len < 0 first, or compare against (int)sizeof(buf).

Trace 3: signed overflow from promoted operands.

C
uint16_t a = 50000, b = 50000;
uint32_t p = a * b;   // a,b -> int; 50000*50000 = 2,500,000,000 > INT32_MAX (2,147,483,647)

The product overflows int before the assignment to uint32_t, which is UB (C11 6.5p5): the widening target does not save you. Fix: uint32_t p = (uint32_t)a * b; → 2,500,000,000, which fits.

Trade-offs. Cast at the point of use, (uint32_t)a * b, minimal diff, but every call site must remember. Or bind an explicit intermediate, uint32_t prod = (uint32_t)a * b;, self-documenting and survives refactors. Masks (& 0xFF) keep a value in range but do nothing about signedness, so they never fix a comparison; use them only when you genuinely want truncation. Fixed-width types everywhere don't help either: uint8_t still promotes. MISRA C:2012 Rule 10.3 (no assignment to a narrower essential type) and Rule 10.4 (same essential type category on both operands) push toward explicit casts; if you're not MISRA-bound, -Wconversion -Wsign-conversion -Werror gets most of the way.

Failure modes and detection.

FailureExampleDetect with
Signed overflow (UB, C11 6.5p5)Trace 3-fsanitize=signed-integer-overflow
Shift into sign bit (UB, 6.5.7p4)1 << 31; use 1u << 31-Wshift-overflow=2
Silent narrowingTrace 1-Wconversion + boundary tests
Signed/unsigned compareTrace 2-Wsign-compare

Validation. Compile with -Wall -Wextra -Wconversion -Wsign-conversion -Wshift-overflow=2 -Werror, run UBSan in CI, and unit-test every arithmetic path at the type boundaries: 0, 127, 128, 255, 32767, 65535. Those are where promotion changes the answer. Re-run boundary tests on the 16-bit-int target before trusting them: the promotion rule flips there.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

Design and validate embedded C/C++ firmware for shifts.

Answer

The 90-second answer

I'd pin three things first: the target's int width, the language version (C11/C17 vs C++20), and whether the shift counts are compile-time constants or come from a register. Then the rule I'd enforce: shift unsigned operands, and keep the count in [0, width). The hardware masks the count; the C standard does not, so masking is not a substitute for validation. I'd make the width explicit in the type, validate any count that isn't a literal, and turn on the sanitizers and warnings that catch the rest.

Why promotion is the trap

<< and >> apply the integer promotions to both operands. On a Cortex-M4 with 32-bit int, a uint8_t becomes int before the shift, so the shift happens in signed 32-bit arithmetic:

C
/* C11, arm-none-eabi-gcc, int = 32-bit */
uint32_t bad(uint8_t b)  { return b << 24; }
uint32_t good(uint8_t b) { return (uint32_t)b << 24; }

Trace bad with b = 0xFF: promotion gives int 255; 255 << 24 is 255 × 2^24 = 4,278,190,080, which exceeds INT_MAX (2,147,483,647). Signed left shift overflow is undefined in C through C17, so the compiler may fold this to 0, to 0xFF000000, or to anything. good shifts a uint32_t: 255u << 24 = 4,278,190,080 < UINT32_MAX (4,294,967,295), defined, result 0xFF000000.

The same code on a 16-bit-int target (MSP430, some PICs) is worse: uint8_t promotes to 16-bit int, and 0xFF << 8 = 65,280 > INT16_MAX (32,767). UB where the host build was fine. That's the host/target difference that bites in review.

Counts from hardware

C
uint32_t scaled(uint32_t x, uint32_t n) { return x << n; }  /* UB when n >= 32 */

The instruction masks n: 32-bit ARM's LSL takes the low 8 bits of the register, x86's SHL the low 5 bits for a 32-bit operand. So n = 40 gives x << 8 on x86 and 0 on ARM: different answers from one source line, and the compiler is entitled to assume n < 32 and delete your check. Validate in C:

C
uint32_t scaled_checked(uint32_t x, uint32_t n) {
    if (n >= 32u) return 0u;   /* or clamp, or raise a fault */
    return x << n;
}

Choices

approachright whencost
mask the count (n & 31u)the count is genuinely modulo-width, e.g. emulating a rotatehides a bad count; silently wrong if n was a real shift
validate and rejectcount comes from a register or untrusted inputa branch and an error path
widen to 64-bityou need the high bits (32×32→64)64-bit multiply/shift is slower on Cortex-M0/M3
unsigned operands everywherealwaysnone

Failure modes and how you catch them

  • Signed left shift overflow (C through C17): silently wrong at -O2. Catch with -fsanitize=shift-base and -Wshift-overflow=2. C++20 defines signed left shift as wrapping modulo 2^N, so this one disappears there: the count range does not.
  • Count out of range: works on the bench, breaks on another core. Catch with -fsanitize=shift-exponent, -Wshift-count-overflow, -Wshift-count-negative, and MISRA C:2012 Rule 12.2 (required: count in [0, width)).
  • Promotion width: catch with -Wconversion on a target build, plus _Static_assert(sizeof(int) == 4, "...") if the code assumes it.
  • Negative right shift: implementation-defined in C (arithmetic on gcc/clang/MSVC, not guaranteed). Catch with -Wsign-conversion; better, don't do it.

Validation plan

Build with -Wall -Wextra -Wconversion -Wsign-conversion -Wshift-count-overflow -Wshift-count-negative -Wshift-overflow=2, run the unit tests under -fsanitize=undefined,shift, and add a table-driven test that shifts by 0, width−1, width and width+1 for every width you use. CERT C INT34-C covers the same ground as a checklist item.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

Design and validate embedded C/C++ firmware for unsigned arithmetic.

Answer

Core answer (first 90 seconds)

State the assumptions before answering: 32-bit Cortex-M target, size_t is 32-bit, untrusted bytes arrive over UART, and the firmware must never read out of bounds. Then: unsigned arithmetic in C and C++ is fully defined (it wraps modulo 2^N, no undefined behaviour) but defined is not correct. Every value derived from a length, offset, index or timestamp is a wrap candidate, and the wrapped result is a small, plausible number that sails through the next bounds check. So the rule is: check before the operation, not after it.

Pick a regime per value:

  • Wrapping is correct for counters, sequence numbers, hashes, and monotonic timestamps compared by difference.
  • Saturating is correct for control outputs: PWM duty, audio, actuator limits.
  • Checked is required for anything that indexes memory or sizes a buffer.

Mechanism

a + b on unsigned is (a + b) mod 2^N. If the invariant is "total ≤ buffer length", the wrapped result is smaller than either operand, so total > len is false and the guard passes. The bug is not the wrap; it is that the check ran on the wrapped value.

Promotion is the second trap: operands narrower than int are promoted to int before the operation, so uint8_t arithmetic is signed arithmetic and comparisons behave differently than the declared type suggests.

Code and trace

C
#include <stdint.h>
#include <stddef.h>

int parse_frame(const uint8_t *buf, size_t len) {
    if (len < 4) return -1;
    uint16_t payload = (uint16_t)(buf[2] | ((uint16_t)buf[3] << 8));
    size_t total = (size_t)payload + 4u;   /* header */
    if (total > len) return -1;
    return consume(buf + 4, payload);
}

Trace on a 16-bit size_t target (MSP430, AVR): buf[2]=0xFF, buf[3]=0xFF → payload = 0xFFFF = 65535. total = (65535 + 4) mod 65536 = 3. 3 > len is false for any len ≥ 3, so the guard passes and consume reads 65535 bytes out of a 100-byte buffer. The same code is safe on a 32-bit target because 65539 fits. Fix: check before adding, if (payload > len - 4) return -1;, len - 4 cannot wrap because len ≥ 4 was already established.

Timeout rollover

C
uint32_t now = millis();                     /* 1 kHz, wraps every 49.7 days */
if (now > deadline) fire();                  /* wrong */
if ((int32_t)(now - deadline) >= 0) fire();  /* correct */

Trace: deadline = 0xFFFFFFF0, now wraps to 0x00000010. now > deadline is false, so the timeout never fires. now - deadline = 0x20 = 32, cast to int32_t is +32 ≥ 0, so it fires. Valid while the interval stays under 2^31 ms (~24.8 days).

Failure modes and detection

  • Packet length wrap → OOB read. Detect with a unit test at payload = 0xFFFF on the narrowest target, Clang -fsanitize=unsigned-integer-overflow (GCC's -fsanitize=undefined does not cover unsigned overflow), and CERT C INT30-C.
  • Pointer offset wrap → OOB. Same detection; INT30-C.
  • Timeout rollover → missed deadline. Test with now and deadline straddling the wrap point.
  • Sentinel collision: 0xFFFF or 0 used as "invalid" collides with a valid value. Enumerate the value space; prefer a separate bool valid.
  • Comparison after promotion: for (uint8_t i = 10; i >= 0; i--) never terminates, because i promotes to int and i >= 0 is always true. -Wtype-limits (in -Wextra) flags it; CERT INT31-C.

Trade-offs

A per-op check costs a compare and a branch: about 2 cycles on Cortex-M0 at 48 MHz, roughly 40 ns. That is free next to a UART byte time (87 µs at 115200 baud), so check every value crossing a trust boundary. Do not check inside a 10 kHz control loop where the value is bounded by construction; assert the invariant once at entry instead. ARM gives saturating add in one instruction (__USAT to a bit position; NEON UQADD8 per byte lane), so prefer it over a branch where the ISA provides it. -ftrapv traps signed overflow only and is useless here; -fwrapv makes signed wrap defined, which is the opposite of what a validation build wants.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Design and validate embedded C/C++ firmware for signed overflow.

Answer

What I'd say first. Signed overflow is undefined behavior in C and C++ (C11/C17 6.5p5; C++17 [expr]), so the compiler is entitled to assume it never happens. The design question is therefore not "how do I detect overflow" but "which operations can I prove stay in range, and where do I pay for a check." My default on embedded: keep counters, masks and bit manipulation unsigned (wrap is defined), and put checked arithmetic only at the boundaries where untrusted or accumulated values enter. ADC scaling, encoder accumulation, protocol length fields.

Assumption: 32-bit MCU, GCC or Clang, C11 or C++17, no FPU needed for the check.

Design. Use C23 <stdckdint.h>, or __builtin_add_overflow on GCC ≥ 5.1 / Clang ≥ 3.8, at the boundary:

C
#include <stdckdint.h>
#include <stdint.h>
#include <stdbool.h>

/* returns false on overflow; caller must not read *acc or next */
bool accumulate(int32_t *acc, int32_t delta) {
    int32_t next;
    if (ckd_add(&next, *acc, delta)) return false;
    *acc = next;
    return true;
}

Trace: *acc = 2147483647, delta = 1 → ckd_add returns true, the caller must not read next. *acc = 2147483640, delta = 5 → next = 2147483645, returns true.

Why the naive check fails. if (a + b < a) is the classic check-after-overflow. GCC and Clang fold it to b < 0, because they assume a + b did not overflow. Trace at -O2: a = 2147483647, b = 1 → the comparison is compiled away, the branch is never taken, and the wrapped value -2147483648 is stored. At -O0 the same source takes the branch. That debug/release divergence is the failure mode, not the wrap itself.

Validation. Three layers:

  1. Build the test image with -fsanitize=signed-integer-overflow,undefined -fno-sanitize-recover=all and run the boundary vectors. UBSan prints runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int' and aborts.
  2. Static: -Wconversion -Wsign-conversion -Wstrict-overflow=5, with CERT C INT32-C and MISRA C:2012 as the review checklist.
  3. Inspect the -O2 disassembly of every overflow check to confirm the branch survived.

Failure modes and how you catch them.

  • Check after overflow: UBSan, or the disassembly step above.
  • Narrowing before check (int64_t sum cast to int32_t, then compared): -Wconversion.
  • Mixed signedness (if (u < s) promotes s to unsigned): -Wsign-compare.
  • Negating INT32_MIN (-x is UB): UBSan; use -(x + 1) or unsigned.
  • Debug wraps, release does not: run the same vectors at -O2 under UBSan.

Choosing between the four options.

approachmechanismwhen it's wrong
range proofoperands bounded so the result fits; zero runtime costproof invalidated when the input source changes
checked builtinckd_add computes and returns an overflow flagbranch cost in a hot loop; you must handle the false path
unsigned arithmeticwrap is defined; freewrong when the value is semantically signed (comparison, division)
-ftrapv / UBSan trapcompiler inserts a trap-ftrapv is documented for add/sub/mul only, not exhaustive; aborts in production

-fwrapv defines the wrap but hides the bug and is not portable to a toolchain that lacks it: use it only to reproduce legacy behavior.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design and validate embedded C/C++ firmware for structure layout.

Answer

What I'd say first

The first question is what the struct is: a wire format, a memory-mapped register block, or an in-memory record that never leaves the chip. The answer changes completely. Assuming it's a wire format shared with a host or another MCU, the common case, the rule is: never memcpy a struct onto the wire, and never let the compiler pick the layout. Serialize field by field into a byte buffer, pin the layout with compile-time asserts, and version the format.

Why the naive version breaks

Padding. Given

C
typedef struct { uint8_t type; uint32_t seq; uint16_t len; } msg_t;

on a 32-bit target seq must sit at a 4-byte offset, so bytes 1–3 are padding, and sizeof(msg_t) is 12 with bytes 10–11 as tail padding. Those five bytes are whatever was on the stack:

C
msg_t m; m.type = 1; m.seq = 0x11223344; m.len = 5;
uint8_t wire[sizeof m]; memcpy(wire, &m, sizeof m);

wire is 01 ?? ?? ?? 44 33 22 11 05 00 ?? ?? on a little-endian target. Five bytes of stack garbage go out over the UART: an info leak, and a checksum computed over the struct is now unstable.

Unaligned access. __attribute__((packed)) shrinks msg_t to 7 bytes and puts seq at offset 1. On ARMv7-M (Cortex-M3/M4/M7) an unaligned LDR/LDRH is handled in hardware, but LDM/STM, LDRD/STRD, and any access to Device memory still fault. On ARMv6-M (Cortex-M0/M0+) every unaligned access raises a HardFault. The trap is taking a member's address: uint32_t *p = &packed.seq;. The compiler loses the packed qualifier and the dereference can fault. GCC and Clang warn with -Waddress-of-packed-member (GCC 9+). The safe read is uint32_t seq; memcpy(&seq, &packed.seq, 4);, which lowers to one unaligned LDR where the target allows it and to a byte-wise sequence on Cortex-M0.

Design

Pin the layout so a compiler or flag change fails the build, not the field:

C
_Static_assert(sizeof(msg_t) == 12, "wire size");
_Static_assert(offsetof(msg_t, seq) == 4, "seq offset");
_Static_assert(offsetof(msg_t, len) == 8, "len offset");

(static_assert in C++11, _Static_assert in C11; offsetof is from <stddef.h>.) Then serialize explicitly, little-endian on the wire, with a version byte:

C
size_t encode(const msg_t *m, uint8_t *out) {
    out[0] = 1;                       /* version */
    out[1] = m->type;
    put_le32(&out[2], m->seq);
    put_le16(&out[6], m->len);
    return 8;
}

put_le32 is memcpy plus __builtin_bswap32 when __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__. Never use bit fields for the wire: their allocation order is implementation-defined and GCC/Clang and MSVC disagree.

Trade-offs

approachsizeaccessportable?use when
natural struct12aligned, fastno: layout varies by compiler, target, flagsin-memory only, never crosses a boundary
packed struct7unaligned; byte-wise on v6-Mlayout fixed, endianness still variesnever for hot paths or DMA; address-of-member is unsafe
explicit serialize8 on wirea few cycles per fieldyesanything shared with a host, another MCU, or flash

Packing is the wrong tool when the struct is a memory-mapped register block: use the vendor header with volatile and exact offsets, never a packed struct, because the compiler may split or reorder accesses.

Validation

  • _Static_assert on size and every offset, in the header, so -fpack-struct or an ABI change breaks the build.
  • -Wpadded (GCC/Clang) to surface padding the moment it appears.
  • Golden vectors: a fixed byte array decoded to a known struct and re-encoded byte-for-byte.
  • A padding-leak test: fill the struct with 0xAA, assign fields, encode, assert no 0xAA survives.
  • pahole on the ELF in CI to diff the real layout against the asserted one.
  • A decoder fuzz target that must reject unknown versions and truncated frames rather than read past the buffer.

Failure modes and how you catch them

  • Padding leak → the 0xAA test, or MSan on the host build.
  • Unaligned fault → HardFault handler logging SCB->CFSR (UFSR UNALIGNED bit); -Waddress-of-packed-member at compile time.
  • Endian mismatch → golden vector with a known byte order, run on both a little- and big-endian target if you have one.
  • Schema evolution → append-only fields, version byte, decoder rejects unknown versions; a corpus of old frames in the regression suite.
  • ABI change → the static asserts, plus a CI job building with the oldest supported toolchain.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design and validate embedded C/C++ firmware for bit fields.

Answer

What I'd say in the first two minutes

Two things decide the design: is the bit field backed by a hardware register or by plain memory, and is the layout fixed by an external spec? For a peripheral register I don't use C bit fields at all: I use explicit masks and shifts. Bit-field allocation order, padding, alignment and signedness are implementation-defined (C11 6.7.2.1p11), and a register write compiles to a read-modify-write that can silently lose an interrupt's update. For packed in-memory data with a frozen ABI, bit fields are fine provided I _Static_assert the layout. Validation is the same either way: compile-time assertions on the masks, a host-side round-trip test, and a disassembly check that the emitted access is the width I intended.

Design: masks for a register

C
/* arm-none-eabi-gcc 13.2, -mcpu=cortex-m4 -mthumb, little-endian */
#include <stdint.h>

#define CTRL_EN_Pos    0u
#define CTRL_EN_Msk    (1u << CTRL_EN_Pos)          /* 0x01 */
#define CTRL_MODE_Pos  1u
#define CTRL_MODE_Msk  (0x3u << CTRL_MODE_Pos)      /* 0x06, 2 bits */
#define CTRL_DIV_Pos   3u
#define CTRL_DIV_Msk   (0x1Fu << CTRL_DIV_Pos)      /* 0xF8, 5 bits */

_Static_assert((CTRL_EN_Msk & CTRL_MODE_Msk) == 0, "EN/MODE overlap");
_Static_assert((CTRL_MODE_Msk & CTRL_DIV_Msk) == 0, "MODE/DIV overlap");
_Static_assert((CTRL_EN_Msk | CTRL_MODE_Msk | CTRL_DIV_Msk) == 0xFFu,
               "low byte not fully covered");

volatile uint32_t *const CTRL = (volatile uint32_t *)0x40000000u;

void ctrl_enable(void) { *CTRL |= CTRL_EN_Msk; }

The assertions catch the two mistakes that actually ship: overlapping fields and a field that silently moved because someone edited a _Pos without the _Msk.

Trace: why |= is dangerous

ctrl_enable() compiles to LDR r3,[r2] / ORR r3,r3,#1 / STR r3,[r2]. If an ISR sets DIV between the LDR and the STR, the STR writes back the stale DIV and the ISR's update is gone. The field reverts on the next read and the bug is intermittent. Fixes, in order of preference: use the hardware's atomic set/clear alias register if the peripheral has one (STM32 GPIOx->BSRR), or wrap the RMW in a short critical section. __atomic_fetch_or is not a safe default here: on Cortex-M it may not be lock-free for a peripheral address.

Validation

  1. _Static_assert on mask disjointness, coverage and sizeof of any bit-field struct.
  2. Host unit test: compile the same header against a plain uint32_t shadow, set each field, read back, assert the raw word. This catches position errors that no compiler will.
  3. arm-none-eabi-objdump -d on the object: confirm a register write is one STR of the intended width, not a widened or split access.

Failure modes and how I'd catch each

FailureWhy it happensDetectionCost if missed
Field order reversedBig-endian target allocates from the MSB; little-endian from the LSBUnit test writing 0x1 and reading the raw wordPeripheral configured wrong, silent
Lost update (RMW)Load-modify-store is not atomic against an ISRScope trace on the bus; read back after an ISR stormField reverts intermittently
Width crosses a unitField offset + width exceeds the 32-bit word, forcing two accessesobjdump; assert offset + width <= 32Bus fault or split write
Volatile semanticsCompiler may widen or narrow the access; GCC's -fstrict-volatile-bitfields (on by default for ARM EABI) forces the declared widthobjdump access widthMissed or duplicated register write
Compiler driftLayout and volatile-access rules differ across GCC/Clang versionsPin the toolchain; run the static asserts in CILayout changes after a toolchain bump

Trade-off

A bit-field struct reads better and is the right choice for in-memory packed data where you own the compiler and can assert the layout. It is the wrong choice for MMIO: no address-of, no offsetof, implementation-defined order, and the same RMW hazard. Masks are verbose and easy to shift wrong, which is exactly what the static asserts and the host test are for. If the layout is fixed by an external spec, generate the masks from that spec rather than hand-writing them.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

Design and validate embedded C/C++ firmware for alignment.

Answer

What I'd say first

Alignment is a C object-model rule before it is a hardware one. A T* must point at storage aligned to _Alignof(T); if it doesn't, the behaviour is undefined (C11 6.3.2.3p7) and the compiler is entitled to assume it does. So the design rule is: never cast a byte buffer, a packed-struct member, or a DMA descriptor to a wider pointer type. Decode with memcpy or byte operations, and assert alignment once, at the boundary where the address enters the system: DMA setup, parser entry, ISR handoff. Whether the target traps is a separate question; it changes the cost of getting it wrong, not the rule.

Why it behaves that way

Three layers can each bite, and they fail differently:

  • Compiler. It assumes T* is aligned. It may merge two 32-bit loads into one 64-bit load, use an aligned SIMD move, or vectorise a loop. Code that passes at -O0 breaks at -O2.
  • ISA. Unaligned support is not uniform:
targetunaligned LDR/LDRHcaveats
ARMv6-M (Cortex-M0/M0+)HardFaultno unaligned support at all
ARMv7-M (Cortex-M3/M4/M7)allowed in Normal memoryDevice/Strongly-ordered memory must be aligned; LDM/STM, LDRD/STRD, LDREX/STREX must be aligned
x86-64allowed for scalar loads/storesMOVDQA/VMOVDQA and CMPXCHG16B require alignment; other locked read-modify-writes on unaligned data take a split-lock penalty or raise #AC
RISC-Vimplementation-definedbase ISA requires natural alignment; misaligned accesses trap or are emulated in firmware
  • Bus and cache. On Cortex-A, a DMA buffer must be aligned to the D-cache line (32 B on Cortex-A9, 64 B on Cortex-A53) and sized to a multiple of it, or a clean/invalidate evicts neighbouring variables.

Worked check

C
struct __attribute__((packed)) hdr { uint8_t ver; uint32_t len; };  /* len at offset 1 */

uint32_t read_len(const uint8_t *buf) {
    uint32_t v;
    memcpy(&v, buf + 1, sizeof v);   /* buf has no alignment requirement */
    return v;
}

Trace with buf = {0x02, 0x78, 0x56, 0x34, 0x12}: memcpy reads bytes at offsets 1..4, 78 56 34 12, and on a little-endian target v == 0x12345678. On ARMv7-M at -O2 GCC typically folds this to one ldr r0, [r1, #1]; with -mno-unaligned-access it becomes four ldrb plus shifts. Both are correct C; only the second is safe on Cortex-M0. Check the disassembly rather than assuming.

Failure modes and how you catch them

  • Address of a packed member taken: &s.len passed to a uint32_t* parameter. Caught by -Waddress-of-packed-member (on by default in GCC 9+). On M0 it faults; on M7 it silently works until the callee uses an aligned-only instruction.
  • DMA buffer not cache-line aligned: symptom is corruption of adjacent variables after a transfer, not a fault. Assert ((uintptr_t)buf % 64) == 0 and size % 64 == 0 at setup.
  • Torn shared variable: an unaligned or 64-bit value read by an ISR and main. Unaligned accesses are not guaranteed single-copy atomic on ARMv7-M. Guard with _Static_assert(ATOMIC_INT_LOCK_FREE == 2) and use _Atomic or a critical section.
  • Packed peripheral struct: unaligned MMIO to Device memory faults on the first write. _Static_assert(offsetof(...) == ...) against the reference manual catches it at build time.

Trade-offs

memcpy is portable and defined; on M0 it costs roughly four byte loads plus shifts versus one ldr. -mno-unaligned-access makes the whole image safe on M0 but pessimises every access: apply it per file. If you own the buffer, alignas(64) plus a one-time assert is cheaper and lets you access directly; __builtin_assume_aligned tells the compiler but checks nothing, so pair it with a runtime assert. Host tests with -fsanitize=alignment and -Wcast-align=strict catch the class of bug before it reaches hardware.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Design and validate embedded C/C++ firmware for strict aliasing.

Answer

Assume GCC 12/Clang 16, C11 or C++17/20, ARM Cortex-M, -O2 with LTO. The question is how to design firmware that never relies on undefined aliasing, and how to prove it.

Design rules. Treat object representation and value representation separately. Never cast a pointer to an unrelated type and dereference it. For type punning, use memcpy in C and C++17, or std::bit_cast in C++20. For byte inspection, unsigned char * is explicitly allowed. For hardware registers and DMA descriptors that must alias, use __attribute__((may_alias)) on the typedef, and keep the access volatile.

C
// UB: C11 6.5p7, C++ [basic.lval]/11
uint32_t u = *(uint32_t*)&f;

// defined
uint32_t u;
memcpy(&u, &f, sizeof u);
C++
// C++20
uint32_t u = std::bit_cast<uint32_t>(f);

Why it matters. The optimizer assumes pointers to different types do not refer to the same object. That lets it reorder or eliminate loads and stores. This function is the classic trap:

C
int foo(float *f, int *i) {
  *i = 0;
  *f = 1.0f;
  return *i;
}

Call it with f and i pointing at the same address. At -O0, *i = 0 writes 0, *f = 1.0f writes 0x3f800000, and the return reads 0x3f800000 = 1065353216. At -O2, GCC 12.2 on x86-64 returns 0: it assumes float* and int* cannot alias, so *i is still 0. That is the bug in production.

Validation. Compile with -O2 -Wstrict-aliasing=2 -flto. Fix every warning. Build a second binary with -fno-strict-aliasing and run the same tests; any behavioral difference is a violation. Run hardware tests that exercise DMA, interrupts and packed structs. Inspect assembly for the expected loads and stores. -fno-strict-aliasing is an escape hatch, not a fix: it disables optimization and hides the defect.

MethodStandardPortabilityCostUse
memcpyC/C++portablecompiles to a movetype punning
std::bit_castC++20portablezero-costtype punning
unionC allowed, C++ UBC portable, C++ notzero-costC only
pointer castUBnonezero-costnever
may_aliasGCC/Clang extensionnon-portablezero-costregisters, DMA

Failure modes. A packed pointer cast, e.g. taking &s.b from struct __attribute__((packed)) { uint8_t a; uint32_t b; } and casting to uint32_t*, causes an unaligned access. On Cortex-M with UNALIGN_TRP set, that is a HardFault; detect it by reading the CFSR UNALIGNED bit. A DMA buffer type pun lets the compiler cache a stale value because it assumes the DMA write and CPU read do not alias; detect it as intermittent data corruption. LTO exposes cross-translation-unit aliasing that -O2 without LTO missed; detect it by comparing behavior with and without -flto. Union punning assumed portable compiles on GCC but is undefined in C++ and can produce wrong values on Clang; detect it with -Wstrict-aliasing=2 and a second compiler.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design and validate embedded C/C++ firmware for volatile boundary.

Answer

Assumptions: Cortex-M7 (STM32F7/H7 class) with D-cache enabled, one ISR, a main loop, and a DMA engine; arm-none-eabi-gcc at -O2, C11.

Core answer

volatile buys exactly two things: the compiler must emit the access, and it must not reorder volatile-to-volatile accesses. It gives no atomicity, no ordering for non-volatile objects, and no cache behaviour. So the design splits three ways: volatile for memory-mapped registers and single-threaded polling; _Atomic plus fences for anything an ISR or a second core observes; cache maintenance plus a barrier for DMA buffers.

Why volatile fails

GCC's manual states that non-volatile accesses may be reordered across volatile accesses. The flag-then-data pattern breaks:

C
volatile int ready;
uint32_t payload;              /* not volatile */

void ISR(void) { payload = 0xDEADBEEF; ready = 1; }

int main(void) {
    while (!ready) { }         /* -O2: loop touches only ready */
    use(payload);              /* load may be hoisted above the loop */
}

Trace at -O2: the loop body reads only ready, so GCC is free to hoist the load of payload above the loop and keep it in a register. use() reads 0 even though the ISR ran. volatile on ready did not order payload.

Torn access is the second failure. On ARMv7-M, byte, halfword and word accesses are single-copy atomic, but a volatile uint64_t is two 32-bit stores; a reader landing between them sees a half-updated value.

The fix

C
#include <stdatomic.h>
_Atomic uint32_t ready;
uint32_t payload;

void ISR(void) {
    payload = 0xDEADBEEF;
    atomic_store_explicit(&ready, 1, memory_order_release);
}
int main(void) {
    while (!atomic_load_explicit(&ready, memory_order_acquire)) { }
    use(payload);
}

ARMv7-M has no LDAR/STLR (those arrive with ARMv8-M), so acquire/release lower to DMB plus a plain LDR/STR. That is a full barrier per handoff: fine for an ISR handoff, wrong for a per-sample loop.

DMA and cache

The Cortex-M7 D-cache is 16 KB with 32-byte lines and is not coherent with DMA. Before the DMA reads a CPU-written buffer: SCB_CleanDCache_by_Addr(buf, len) then __DSB(). Before the CPU reads a DMA-written buffer: SCB_InvalidateDCache_by_Addr(buf, len). Both need 32-byte-aligned addresses with the length rounded up, or you clean or invalidate a neighbouring line.

When volatile is the right tool

  • MMIO: *(volatile uint32_t *)0x40020000 = 1;. The access must not be elided or merged.
  • volatile sig_atomic_t in a POSIX signal handler.
  • Single-threaded polling of a hardware register.

Deciding criterion: is another agent (ISR, second core, DMA engine) observing the same memory outside the C memory model? If yes, volatile alone is insufficient.

Failure modes and detection

failuresymptomdetection
torn 64-bit readintermittent wrong valueseqlock retry counter, or read twice and compare
reordered flag/datastale payload under -O2arm-none-eabi-objdump -d on the loop; host build under -fsanitize=thread
dirty cache lineDMA reads stale bytesdisable D-cache; if the bug vanishes, it is coherence
spin without timeouthang if the ISR never fireswatchdog reset counter
64-bit atomic not lock-freesilent lock table, priority inversioncheck ATOMIC_LLONG_LOCK_FREE

Validation

Build at -O2 -mcpu=cortex-m7, disassemble the handoff and confirm the DMB is present. Stress the path: toggle the ISR at 10 kHz while main reads, count mismatches. The count must be zero. Run the same logic on a host build under TSan. Put a watchdog on every spin.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design and validate embedded C/C++ firmware for object lifetime.

Answer

Assumptions I'd state up front: bare-metal Cortex-M with an RTOS, C11 and C++17, heap banned in the safety path, ISRs sharing data with threads. The real question is who owns the storage and whether that storage outlives every reference to it.

A pointer or reference is valid only while the object's lifetime is running. In C that's storage duration: automatic ends at block exit, static at program end, allocated at free. In C++ a class object's lifetime ends when its destructor starts, or when storage is released or reused, whichever comes first. So the design question is: what is the longest-lived reference, and does the owner outlive it?

Three ownership models, chosen by instance count and lifetime:

Caller storage. The callee writes into memory the caller owns: int parse(const char *s, result_t *out). The object lives in the caller's frame, so it dies when the caller returns; anything outliving the caller must copy. Cost: the caller sizes the buffer up front, and you can't return a variable-length result without a second call. Use it for synchronous, single-call results.

Static storage. File-scope or function-local static. Justify it when there is exactly one instance by design (one UART, one config) or when the standard you certify against bans allocation. Costs: not reentrant, shared between ISR and thread so it needs a critical section or a lock-free handoff, and the RAM is never reclaimed. Don't use it for anything with more than one instance or a lifetime shorter than the program.

Bounded pool. A fixed block allocator over a static array. No fragmentation, O(1) alloc and free, but capacity is fixed: size the worst case and handle exhaustion explicitly. Use it for N instances with a bounded concurrent count: queue nodes, DMA descriptors.

modellifetimecostuse when
caller storagecaller's framecaller sizes it; no variable-length returnsynchronous, one result
staticprogramnot reentrant; ISR/thread race; RAM never freedexactly one instance, or allocation banned
bounded pooluntil free()fixed capacity; must handle exhaustionN bounded concurrent instances
C
/* C11, abbreviated */
static msg_t pool[16];
static bool  used[16];

msg_t *msg_alloc(void) {
    for (int i = 0; i < 16; i++)
        if (!used[i]) { used[i] = true; return &pool[i]; }
    return NULL;
}
void msg_free(msg_t *m) {
    size_t i = (size_t)(m - pool);
    assert(i < 16 && used[i]);
    memset(m, 0xEF, sizeof *m);
    used[i] = false;
}

Trace: the first msg_alloc returns &pool[0], the second &pool[1]. msg_free recovers the index by pointer subtraction, which is defined only because m points into pool; a pointer from anywhere else is UB, which is why the assert checks the index rather than the pointer. After free the block is filled with 0xEF bytes, so a use-after-free reads 0xEFEFEFEF instead of stale data.

Failure modes, each with detection:

  • Callback after return: a handler captures a pointer to a stack local, then the function returns and the stack is reused. Detect with a stack-painting high-water mark and by running the callback path under ASan on the host build.
  • DMA from a stack buffer: the transfer is still running when the function returns. Check the DMA-complete flag before the buffer's scope ends, or place a canary word after the buffer.
  • Async queue holding a pointer: the producer's frame dies before the consumer runs. The pool's poison-on-free turns this into a visible 0xEFEFEFEF read in debug.
  • C++ temporary: std::string_view sv = std::string("x"); dies at the semicolon. clang-tidy bugprone-dangling-handle and -Wdangling-gsl catch the common shapes.
  • Reset-retained stale address: a pointer in a .noinit section survives a warm reset but the object doesn't. Guard the retained struct with a magic value and CRC, and re-init on mismatch.

Validation: MISRA C:2012 for the C side, clang-tidy plus ASan/UBSan on a host build of the portable logic, an MPU guard region around the pool, and a pool high-water counter exported to telemetry.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design and validate embedded C/C++ firmware for C++ static initialization.

Answer

Assume bare-metal Cortex-M, GCC 12 / arm-none-eabi, C++17, newlib, no OS. The answer: push as much initialization as possible into constant initialization so it lands in .data/.bss and costs nothing at runtime; when you can't, put dynamic initialization behind one explicit ordered init function called from main, and validate by inspecting .init_array in the linked image.

Mechanism. A global whose constructor is constexpr (or zero-initialized) is constant-initialized: the startup code memcpys .data from flash and zeroes .bss, and no code runs. Any global whose constructor is not constexpr gets compiled into a function, and the compiler emits a pointer to it into the ELF section .init_array (symbols __init_array_start/__init_array_end on ARM EABI). newlib's __libc_init_array, called from crt0 before main, walks __preinit_array, then .init_array, calling each pointer in order. That order is link order across translation units: the standard leaves it unspecified, which is the whole fiasco.

Design. (1) constexpr everything you can. (2) If you need runtime init, write one void init_all() called explicitly at the top of main, in a documented order; no cross-TU dependencies inside constructors. (3) Any global that must have a constructor stays self-contained: no other globals, no hardware, no allocation. GCC's init_priority(101..65535) exists but only orders within one link and breaks silently when files move.

Validation. readelf -S firmware.elf | grep init_array: confirm the section exists and its size matches the constructor count you expect. nm firmware.elf | grep _GLOBAL__sub_I_ lists each dynamic initializer. Check the linker script KEEPs .init_array: with --gc-sections and no KEEP, the section is dropped and your constructors silently never run. objdump -d the region to see what each one touches.

Trade-offs. Dynamic init is fine for a self-contained object with no dependencies and no hardware: a lookup table built at startup, say. It is not fine for anything that reads another global or a peripheral.

Failure modes.

  • Static init order fiasco: A's constructor reads global B in another TU that hasn't run, so it reads zeroed .bss. Detect: a constructor sees a zero or null it shouldn't.
  • Hardware before clocks: a constructor writes a peripheral register before RCC enable → bus fault before main. Detect: hard fault with PC inside .init_array.
  • Hidden heap: a constructor uses std::string/std::vector, pulling in malloc before the heap is sized. Detect: map file shows malloc linked in, or fault in _sbrk.
  • Exception before handlers: a constructor throws → __cxa_throw → abort before your fault handler is installed. Detect: __cxa_throw in the map; use -fno-exceptions if you don't need them.
  • Boot budget: each constructor is a call. Measure with DWT->CYCCNT around __libc_init_array. 40 constructors × ~200 cycles at 80 MHz ≈ 100 µs (hypothetical: measure yours).
C++
// bad: ctor runs from .init_array before main, order unspecified
Driver g_driver;                 // touches RCC in its ctor

// good: constant init + explicit ordered init
constexpr Config kCfg{115200};
void init_all() { enable_clocks(); g_driver.init(); }
int main() { init_all(); /* ... */ }

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design and validate embedded C/C++ firmware for exceptions and RTTI.

Answer

Assumptions. Bare-metal Cortex-M4, arm-none-eabi-gcc 13, C++17, no OS, roughly 512 KB flash and 128 KB RAM, and at least one third-party static library you cannot rebuild. On Cortex-A under Linux the calculus flips and I would keep exceptions.

Core answer. Default the whole image to -fno-exceptions -fno-rtti, applied to every translation unit including third-party archives, and enforce that in CI rather than in a wiki page. Exceptions buy constructor failure and non-local error propagation; on bare metal they cost flash for unwind tables and give an unbounded worst-case latency you cannot put in a WCET budget. RTTI buys dynamic_cast and typeid; embedded dispatch is usually CRTP, std::variant, or a tagged union, so you rarely need it. The escape hatch is a C ABI boundary: if a vendor library throws, catch at the edge and convert to an error code. Never let a throw cross into -fno-exceptions code.

What the flags do.

flageffectcost
-fno-exceptionsthrow/try/catch are compile errors in that TU; no LSDA in .gcc_except_tablethrowing STL paths abort
-fno-rttino _ZTI/_ZTV typeinfo; dynamic_cast/typeid on polymorphic types are compile errorsno runtime type queries
-funwind-tableskeeps unwind data for backtraces without exceptionsflash per function

Whether -fno-exceptions alone drops the unwind sections is target-dependent: .ARM.exidx/.ARM.extab on ARM, .eh_frame on x86-64. Measure with readelf -S and arm-none-eabi-size -A instead of assuming.

Why a stripped frame terminates. Suppose libvendor.a was built with the default -fexceptions and app.o with -fno-exceptions:

  1. libvendor.a executes throw.
  2. __cxa_throw calls _Unwind_RaiseException in libgcc.
  3. The unwinder walks frames using the FDEs in .ARM.exidx. It reaches a frame in app.o that has no FDE: confirm with readelf --unwind.
  4. With no FDE the unwinder cannot continue and returns _URC_END_OF_STACK.
  5. __cxa_throw sees no handler was found and calls std::terminate().
  6. std::terminate() runs the installed handler; the default is abort().

STL interaction. libstdc++ guards its throw helpers on __cpp_exceptions; with exceptions off, bits/functexcept.h defines them to call std::abort(). So v.at(i) out of range aborts rather than throwing std::out_of_range. The code still compiles, and the failure is a hard fault, not a catchable error.

Failure modes and detection.

  • Mixed flags across TUs. The linker says nothing. Assert the flag set per object from compile_commands.json in CI, and run nm -C image.elf | grep -E '__cxa_throw|_Unwind|_ZTI': anything that shows up is a library you did not rebuild.
  • A throw crossing a no-exception frame, as traced above. Detect with std::set_terminate logging __builtin_return_address(0), or a breakpoint on abort.
  • A C TU in the middle of the unwind path. C has no exceptions, but if a C++ throw must unwind through a C frame, that C TU needs -funwind-tables; without it you get the same end-of-stack terminate.
  • A noexcept violation, or a throw from a destructor during unwinding, calls std::terminate with no unwinding at all. Only mark a function noexcept if it truly cannot fail.
  • A third-party RTTI dependency: one dynamic_cast inside a vendor archive pulls _ZTI/_ZTV into the image. Detect with nm --size-sort and readelf -S | grep _ZTI.

Deciding criteria. Keep exceptions if you are hosted, if constructors must report failure, or if a library you cannot rebuild throws. Drop them if you have a hard-real-time bound, a tight flash budget, or you already use return codes or std::expected. Keep RTTI only if you actually call dynamic_cast; otherwise drop it and dispatch on a tag or std::variant.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design and validate embedded C/C++ firmware for optimization validation.

Answer

Core answer (first 90 seconds)

Treat "optimization validation" as one question: does the binary you ship, built with the optimizer on, behave the same as the reference build you debugged, and does its timing, stack and fault behaviour stay inside budget? State assumptions up front: bare-metal Cortex-M4 (STM32F4-class) at 168 MHz, arm-none-eabi-gcc 13.2, release flags -O2 -flto -g, reference flags -O0 -g3, HIL rig with SWD via J-Link and a UART capture.

Then build a matrix, not a build. Run one test suite across every configuration and diff observable behaviour: UART byte stream, GPIO toggles, DWT->CYCCNT cycle counts, stack high-water marks. A single build proves nothing about the others.

On the design side: keep one test entry point compiled into every build, avoid #ifdef DEBUG that changes behaviour, and make timing observable (DWT, GPIO) rather than inferred.

Why the bug disappears

-O0 and -O2 are different programs. Instrumentation adds code, changes register allocation and inlining decisions, moves stack frames, and shifts timing. A race that needs a 40-cycle window closes once a debug print costs 87 µs. Undefined behaviour is the other half: at -O0 the compiler reloads memory on every access; at -O2 it assumes no aliasing and keeps the value in a register.

C
/* arm-none-eabi-gcc 13.2, -O2 -flto */
float read_after_store(float *f, int *i) {
    *i = 1;
    return *f;   /* UB: -O2 may return the pre-store value; -O0 reloads */
}

That is UB, so no output is guaranteed: the point is that the two builds can disagree, and only the release build ships.

Trade-offs

-O0 is the wrong ground truth for timing: it is typically 2-5x slower and its stack depth is not the shipped one. Host sanitizers (ASan/UBSan) catch aliasing and out-of-bounds, but they cannot run on the target and they change timing, so they validate logic, not the release binary. LTO makes .map attribution harder: a symbol can land in a different section than the source suggests. -fno-strict-aliasing buys safety at a measurable cost in hot loops; use it only where you have proven the aliasing.

Failure modes and how you detect them

gapdetection
-O0-only validationbuild -O2 -flto, rerun the same HIL suite, diff UART bytes
sanitizer host onlyon-target MPU fault handler + stack painted 0xA5A5A5A5, read high-water mark
.map from different flagsarchive one .map per build, assert .text/.bss deltas
debug asserts alter timingDWT->CYCCNT around the ISR, assert worst case ≤ 168 cycles (1 µs at 168 MHz)
compiler upgrade unqualifiedpin the toolchain, diff objdump of hot functions across versions

Arithmetic that decides it

At 168 MHz one cycle is 5.95 ns, so a 1 µs ISR budget is 168 cycles. A single character over 115200 8N1 costs 10 bits / 11520 B/s = 86.8 µs: 87x the whole ISR budget. That is why a printf inside an assert turns a timing failure into a passing test.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Design and validate embedded C/C++ firmware for diagnostics.

Answer

Clarify first. "Diagnostics" is three different designs: on-target fault capture (what happened when it crashed), boot self-test (is the hardware sane), and health telemetry (is it degrading). I'll assume Cortex-M4F, arm-none-eabi-gcc 13.2, C11, MISRA C:2012, no RTOS, and 4 KB of retained RAM that survives a warm reset but not power loss. If your diagnostics are a UART printf, most of this collapses to log levels: say so and move on.

Design. A fixed ring of fault records in retained RAM, published head-last so a reset mid-write can never expose a torn record:

C
/* arm-none-eabi-gcc 13.2, Cortex-M4F, C11 */
#define FAULT_RING_LEN 64u   /* 64 x 16 B = 1 KB of the 4 KB retained budget */

typedef struct {
    uint32_t seq;        /* monotonic across resets */
    uint32_t pc;         /* stacked PC at fault */
    uint32_t lr;         /* EXC_RETURN */
    uint16_t fault_id;   /* HARD_FAULT, MPU, STACK_OVF, ... */
    uint8_t  boot;       /* boot counter */
    uint8_t  crc8;       /* CRC-8, poly 0x07, init 0x00, over the first 15 bytes */
} fault_rec_t;           /* 16 B, no padding */

static fault_rec_t g_ring[FAULT_RING_LEN] __attribute__((section(".retained")));
static uint32_t    g_head __attribute__((section(".retained")));

void fault_push(uint16_t id, uint32_t pc, uint32_t lr)
{
    fault_rec_t *r = &g_ring[g_head % FAULT_RING_LEN];
    r->seq = g_head;
    r->pc = pc;
    r->lr = lr;
    r->fault_id = id;
    r->boot = (uint8_t)g_boot_count;
    r->crc8 = crc8((const uint8_t *)r, 15);
    g_head++;            /* published last */
}

Trace it: g_head starts at 0, so the first fault writes slot 0, CRCs bytes 0-14, then advances head to 1. The reader walks slots 0..head-1 and rejects any record whose CRC-8 mismatches. A reset between the CRC write and the increment leaves head pointing at the slot being written, so the half-written record is never published; the CRC is the second line of defence, catching corruption of already-published records (bit flips in retained RAM, a stray DMA write). After 64 pushes the index wraps and overwrites the oldest record; seq keeps increasing, so ordering survives the wrap and the reader takes the last min(head, 64) records. 64 x 16 B = 1 KB, a quarter of the retained budget, leaving room for the boot counter and self-test results.

Capturing pc/lr needs the stacked exception frame, not the handler's own registers:

C
void HardFault_Handler(void)
{
    uint32_t *sp = (__get_LR() & 0x4u) ? (uint32_t *)__get_PSP()
                                       : (uint32_t *)__get_MSP();
    /* frame: R0 R1 R2 R3 R12 LR PC xPSR [S0-S15 FPSCR ...] */
    fault_push(HARD_FAULT, sp[6], sp[5]);
    NVIC_SystemReset();
}

EXC_RETURN bit 2 selects PSP vs MSP; the frame layout is R0 R1 R2 R3 R12 LR PC xPSR, so sp[6] is the faulting PC and sp[5] the return address. An FPU-extended frame appends S0-S15 after xPSR, so those offsets still hold.

Validate, and validate the validator. A diagnostic that never fires is a false negative you ship.

validatemethodpass criterion
fault capturetrigger MPU violation and divide-by-zero from a test hookrecord with the faulting PC and correct fault_id, CRC valid
retentionNVIC_SystemReset() in a 1000-iteration loopboot counter increments by 1000, zero lost or torn records
ring wrappush 100 recordsoldest 36 overwritten, seq monotonic, no CRC failures
self-testforce a flash CRC mismatchboot self-test fails, device enters safe mode
warning baseline-Wall -Wextra -Werror per compiler versionzero new warnings vs. the checked-in baseline

Trade-offs. Per-record CRC-8 costs 1 byte per record and localizes a torn write; a whole-buffer CRC-32 costs 4 bytes total but tells you only that something is corrupt. Retained RAM survives warm resets, not power loss: post-power-loss evidence means mirroring to external flash, which brings 100k-cycle erase limits and wear leveling. A blocking boot self-test (RAM march, flash CRC) costs tens of ms of boot time; run it in the background if the boot budget is tight, but then a fault during self-test must not be masked.

Failure modes and how you catch them. Warning flood ignored: check in a baseline file per compiler version and fail CI on any diff; every suppression is a #pragma GCC diagnostic with a comment naming an owner and a ticket. Blanket (void*) casts hiding type errors: -Wcast-align -Wstrict-aliasing, MISRA rule 11.x. A new compiler blocking release: pin the toolchain in CI and run the new version as a non-blocking job first, triaging the diff. Generated and hand-written code mixed: separate warning baselines per directory, generated code excluded from -Werror but still analyzed. Analyzer false negative assumed impossible: cross-check two analyzers (clang-tidy plus Cppcheck) and back it with fault injection, measuring diagnostic-path coverage with MC/DC where the standard demands it. Stack overflow corrupting the very RAM the handler writes to: reserve a guard region and check MSP against it before fault_push, or the record is garbage.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Design and validate embedded C/C++ firmware for memory failure evidence.

Answer

What I'd say first

Assume a bare-metal Cortex-M4 (STM32F4-class), arm-none-eabi-gcc 12.3, no MMU, MPU present, 128 KiB RAM, hard real-time control loop. "Memory failure evidence" means two things I design in rather than bolt on: a static budget proving the worst case fits, and runtime proof the shipped image stayed inside it. The design decisions are paint the stack, guard it with the MPU, track heap high-water with hooks, and make allocation failure a tested path. Validation runs the fault/stress suite against the exact ELF and archives the numbers with the build-id.

Static side

-fstack-usage emits a .su file with each function's frame size; -Wstack-usage=1024 fails the build when one exceeds budget. -fcallgraph-info (GCC 12+) plus the .su files gives a worst-case path. -Wl,--print-memory-usage and the map file give section sizes. Caveat: .su does not see indirect calls or recursion. Flag every function-pointer table and any recursion by hand.

Dynamic side

Paint the stack with 0xA5A5A5A5 at startup, then scan for the deepest untouched word.

C
/* arm-none-eabi-gcc 12.3, Cortex-M4, -O2 */
#define STACK_FILL 0xA5A5A5A5u
extern uint32_t _sstack, _estack;   /* from linker script */

void stack_paint(void) {
    uint32_t *p = &_sstack;
    while (p < &_estack) *p++ = STACK_FILL;
}

size_t stack_high_water(void) {
    uint32_t *p = &_sstack;
    while (p < &_estack && *p == STACK_FILL) p++;
    return (size_t)((uint8_t *)&_estack - (uint8_t *)p);
}

Trace: the stack spans 0x20000000–0x20001000 (4 KiB). stack_paint writes 0xA5A5A5A5 to all 1024 words. After the workload the deepest excursion reached 0x20000C00, so words 0x20000000–0x20000BFF (768 words) still hold the pattern; the scan stops at p = 0x20000C00 and returns 0x20001000 − 0x20000C00 = 0x400 = 1024 bytes. Peak stack = 1024 of 4096 bytes. Caveat: a legitimate 0xA5A5A5A5 value stored on the stack stops the scan early and under-reports. Pick a pattern that cannot be a valid datum, or cross-check against the MPU.

Heap: wrap malloc/free with counters, or on FreeRTOS use xPortGetMinimumEverFreeHeapSize() and uxTaskGetStackHighWaterMark(). Minimum-ever, not current: the transient is the number that matters.

MPU: mark the 32 bytes below the stack limit no-access so overflow raises a MemManage fault at the write instead of silently corrupting the heap.

budgetmeasuredmargin
stack 2048 B1024 B peak1024 B
heap 16 KiB11.2 KiB min-ever-free4.8 KiB
.text 96 KiB91.4 KiB4.6 KiB

Trade-offs

Static vs dynamic: static covers paths the test never ran; dynamic covers the real workload but only what ran. Use static for the budget, dynamic to confirm it holds. Pattern vs MPU guard: the pattern is free but post-hoc and foolable; the MPU faults immediately but costs a region and 32-byte alignment. Fixed pools vs malloc: pools give deterministic high-water and no fragmentation; malloc needs hooks and can fragment.

Failure modes and detection

  • Wrong binary measured: record readelf -n build-id and map hash in the evidence bundle; CI diffs them.
  • Average instead of peak: report minimum-ever-free, not current free.
  • ISR path absent: coverage on ISR entry, or force max nesting in the stress run.
  • Allocation failure untested: a fault-injection allocator fails the Nth call; assert the degraded path runs.
  • Map symbols stripped: keep an unstripped ELF for analysis, strip only the shipped image.
  • Crash evidence overwritten: reserve a noinit RAM region for the fault frame with a CRC.

Curated: · Written: · Reviewed:

Difficulty: Hard