Embedded C and C++ Programming Questions
Writing C and C++ for resource-constrained microcontrollers and bare-metal or RTOS firmware, where every language construct maps to hardware behavior. Covers the C and C++ language craft firmware code relies on (header guards and the one-definition rule, macros versus const, inline and constexpr, enum class, callback and dispatch tables, static locals, const-correctness, bounded string handling, compile-time lookup tables, and overridable default handlers through weak symbols), the const and volatile qualifiers, memory-mapped register access (including bitfield versus mask-and-shift modelling) and read-modify-write patterns, compiler pragmas and optimization flags, packing structs to match hardware register and wire layouts, linker scripts, memory maps, placement across flash, SRAM, tightly coupled and backup memory, and startup code, static versus dynamic allocation, memory pools, bump, first-fit, buddy and slab embedded allocators, heap fragmentation, out-of-memory strategy and finding leaks or heap corruption without desktop tools, DMA-safe buffer allocation, stack sizing and overflow detection, memory protection unit regions for isolating tasks, fixed-point arithmetic, code-size reduction, the cost of C++ features such as exceptions, virtual dispatch and templates in firmware, and whether a given access is atomic on the target hardware (word size, read-modify-write on registers). Boundary: general-purpose C++ application craft (STL containers and algorithms, template metaprogramming), language-defined struct padding rules, inline assembly, interrupt and real-time scheduling theory, general concurrency primitives, peripheral buses and drivers, assembly-level debugging, and firmware architecture and ring-buffer streaming are covered elsewhere.
Explain how a linker script decides where code, initialised data and uninitialised data land on a microcontroller. Show how you would keep a diagnostics buffer out of the startup zeroing so it survives a warm reset, and how C code finds the boundaries of a section.
Sample Answer
How the linker decides where things go. The compiler places every function and variable in a named section (an object file's labelled chunk of bytes), and the linker script maps input sections to output sections and output sections to memory regions. A script has two parts:
MEMORYdescribes the hardware: name, start address and length of each region (flash, RAM, and here a small third region).SECTIONSlists output sections in order, each with the input sections it collects (*(.text*)means every input section starting.text) and a region (> FLASH).
The usual layout for a microcontroller:
- Code (
.text) and read-only data (.rodata, such asconsttables): into flash. They need no copy; the CPU reads them in place. - Initialised data (
.data, globals with a non-zero initial value): the values must persist when power is off, so they are stored in flash, but the variables must live in RAM where they can change. The script gives.dataa run address in RAM and a load address in flash (> RAM AT > FLASH), and exports where the stored copy starts (_sidata = LOADADDR(.data)). Startup code copies the bytes from the load address to the run address beforemain. - Zero-initialised data (
.bss, globals with no initialiser or an initialiser of zero): nothing is stored in flash, because every byte is zero. The section only reserves RAM, and startup code zeroes it. - Uninitialised data that must not be touched (
.noinit): reserved RAM that startup neither copies into nor zeroes, so whatever was there before a warm reset (a reset while power stays on and RAM keeps its contents, as opposed to a cold start, where power was removed and RAM holds arbitrary bits) is still there.
Keeping a diagnostics buffer out of the startup zeroing. Three things must all be true:
- The variable is in its own section, with no initialiser (an initialiser would give it contents to load):
Diag g_diag __attribute__((section(".noinit")));. - The linker script places that section outside the
[_sbss, _ebss)range that startup zeroes, and marks it(NOLOAD)so nothing is stored in the flash image. The script below gives it its ownNOINITmemory region at the top of RAM. A fixed address matters: a different firmware version, or a bootloader, reading the buffer after a reset must find it where the previous program left it, and a region of its own does not move when.dataand.bssgrow. The stack top (_estack) is set to the end of the ordinary RAM region, below the buffer. - The startup code never clears it, whether by a full-RAM clear or through another section. If a vendor startup file or the device's reset logic initialises all RAM (some parts with error-correcting RAM must write every word once after power-up, so the stored check bits are valid before the first read; a startup file for such a part often clears all of RAM for that reason), the buffer is lost whatever the linker script says, so confirm what your device and startup code do.
Whether RAM contents survive a reset depends on the device and the kind of reset, and normally they do not survive a power loss, so the buffer carries its own proof of validity: a magic number and a CRC-32 over the content. At boot, a valid buffer means a warm reset and its counters continue; an invalid one is power-up garbage or corruption, and the buffer is cleared and restarted.
How C code finds section boundaries. The script defines symbols (_sdata = .;, _ebss = .;). C declares them as extern objects and uses only their address, never their value: extern uint8_t _snoinit[], _enoinit[]; then _enoinit - _snoinit is the section's size, and &_sidata, &_sdata, &_edata bound the .data copy. A symbol's "value" is an address the linker computed, so reading it as a variable would fetch whatever bytes lie at that address.
Files. diag.h and diag.c are the portable logic, which was also run on the host. startup.c (reset handler, vector table and a small main) and link.ld (the linker script) are the target side. The header, diag.h:
#include <stdint.h>
#define DIAG_MAGIC 0xD1A60001u
typedef struct {
uint32_t magic;
uint32_t boot_count; /* warm resets seen since the last cold start */
uint32_t last_event;
uint8_t log[228];
uint32_t crc; /* CRC-32 of every byte before this field */
} Diag;
extern Diag g_diag;
void diag_boot(void); /* returns with g_diag valid; sets g_diag.boot_count to 0 on a cold start */
int diag_was_warm(void);
Reading crc32 below: c starts as all ones. Each input byte is XORed into the low 8 bits of c; then eight times the register is shifted right one bit and, if the bit that fell off was 1, XORed with 0xEDB88320 (the bit-reversed form of the standard CRC-32 polynomial). The expression 0u - (c & 1u) produces all ones when that bit is 1 and zero otherwise, so the XOR happens without a branch. The result is inverted at the end. Any change to any byte changes the result with overwhelming probability, which is what valid() relies on. The implementation, diag.c:
#include "diag.h"
#include <stddef.h>
/* No initialiser on purpose: the startup code must neither load nor clear this object. */
Diag g_diag __attribute__((section(".noinit")));
static uint32_t crc32(const uint8_t *p, size_t n) {
uint32_t c = 0xFFFFFFFFu;
while (n--) {
c ^= *p++;
for (int i = 0; i < 8; i++) c = (c >> 1) ^ (0xEDB88320u & (0u - (c & 1u)));
}
return ~c;
}
static int valid(void) {
return g_diag.magic == DIAG_MAGIC &&
g_diag.crc == crc32((const uint8_t *)&g_diag, offsetof(Diag, crc));
}
static int warm;
void diag_boot(void) {
warm = valid();
if (warm) {
g_diag.boot_count++;
} else { /* power-up garbage or corruption: start clean */
for (unsigned i = 0; i < sizeof g_diag; i++) ((volatile uint8_t *)&g_diag)[i] = 0;
g_diag.magic = DIAG_MAGIC;
}
g_diag.crc = crc32((const uint8_t *)&g_diag, offsetof(Diag, crc));
}
int diag_was_warm(void) { return warm; }
In diag_boot, the clearing loop writes through a volatile uint8_t *. volatile tells the compiler that every one of those byte stores is a real memory access that must be performed as written, in order. Without it the compiler may fold or reshape the loop (for example into a library memset call, which a freestanding image may not provide), because as far as it knows nothing reads the bytes back before they are overwritten again. The target startup, startup.c:
#include <stdint.h>
#include "diag.h"
extern uint32_t _estack, _sidata, _sdata, _edata, _sbss, _ebss;
extern uint8_t _snoinit[], _enoinit[];
int main(void);
void Reset_Handler(void) {
uint32_t *src = &_sidata;
for (uint32_t *dst = &_sdata; dst < &_edata; ) *dst++ = *src++; /* .data: copy initial values from flash */
for (uint32_t *dst = &_sbss; dst < &_ebss; ) *dst++ = 0; /* .bss: zero. .noinit is outside this range */
main();
for (;;) { }
}
__attribute__((section(".isr_vector"), used))
const uint32_t vector_table[2] = { (uint32_t)&_estack, (uint32_t)Reset_Handler };
uint32_t counter = 5; /* initialised: .data */
uint32_t samples[64]; /* uninitialised: .bss */
const uint32_t table[4] = {1, 2, 3, 4}; /* const: .rodata, stays in flash */
int main(void) {
diag_boot();
samples[0] = counter + (uint32_t)(_enoinit - _snoinit) + table[1];
for (;;) { }
}
The linker script, link.ld:
ENTRY(Reset_Handler)
MEMORY
{
FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 256K
RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 64K - 256 /* normal RAM, stack at its top */
NOINIT (rw) : ORIGIN = 0x2000FF00, LENGTH = 256 /* retained across warm resets */
}
_estack = ORIGIN(RAM) + LENGTH(RAM);
SECTIONS
{
.isr_vector : { KEEP(*(.isr_vector)) } > FLASH
.text : { *(.text*) *(.rodata*) . = ALIGN(4); } > FLASH
_sidata = LOADADDR(.data); /* where the initial values sit in flash */
.data : { . = ALIGN(4); _sdata = .; *(.data*) . = ALIGN(4); _edata = .; } > RAM AT > FLASH
.bss : { . = ALIGN(4); _sbss = .; *(.bss*) *(COMMON) . = ALIGN(4); _ebss = .; } > RAM
.noinit (NOLOAD) : { . = ALIGN(4); _snoinit = .; *(.noinit*) . = ALIGN(4); _enoinit = .; } > NOINIT
ASSERT(_enoinit - _snoinit <= LENGTH(NOINIT), "noinit region overflow")
}
Host run of the validity logic. diag.c and a small driver (host_test.c, below) that simulates reset by calling diag_boot again on the same RAM, compiled with gcc -O2 -Wall -Wextra -fsanitize=address,undefined diag.c host_test.c in a gcc:14 container (GCC 14.4, aarch64), printed:
#include <stdio.h>
#include <string.h>
#include "diag.h"
static void boot(const char *label) {
diag_boot();
printf("%-34s warm=%d boot_count=%u\n", label, diag_was_warm(), g_diag.boot_count);
}
int main(void) {
printf("sizeof(Diag) = %zu\n", sizeof(Diag));
memset(&g_diag, 0xA5, sizeof g_diag); /* what power-up RAM might hold */
boot("power-up garbage:");
boot("warm reset (RAM kept):");
boot("warm reset (RAM kept):");
g_diag.log[10] ^= 1; /* one flipped bit */
boot("after one corrupted byte:");
boot("warm reset again:");
return 0;
}
sizeof(Diag) = 244
power-up garbage: warm=0 boot_count=0
warm reset (RAM kept): warm=1 boot_count=1
warm reset (RAM kept): warm=1 boot_count=2
after one corrupted byte: warm=0 boot_count=0
warm reset again: warm=1 boot_count=1
Target build. Compiled and linked, not run, with GNU Arm Embedded arm-none-eabi-gcc 14.2.1 (-mcpu=cortex-m4 -mthumb -O2 -Wall -Wextra -ffreestanding -nostdlib -nostartfiles -T link.ld startup.c diag.c -o fw.elf) in the same container. The file order matters for the addresses below: with startup.c first the reset handler sits right after the vector table, at 0x08000008; with diag.c first it would follow diag_boot. No warnings. Inspecting the result (excerpts: the nm listing keeps only the symbols discussed below, and the section and program tables omit the debug, string-table and segment-mapping parts that the same commands also print):
== section headers (readelf -S -W) ==
[Nr] Name Type Addr Off Size ES Flg Lk Inf Al
[ 1] .isr_vector PROGBITS 08000000 010000 000008 00 A 0 0 4
[ 2] .text PROGBITS 08000008 010008 000144 00 AX 0 0 4
[ 3] .data PROGBITS 20000000 020000 000004 00 WA 0 0 4
[ 4] .bss NOBITS 20000004 020004 000104 00 WA 0 0 4
[ 5] .noinit NOBITS 2000ff00 02ff00 0000f4 00 WA 0 0 4
== symbols (nm -n) ==
0800013c T table
0800014c A _sidata
20000000 D _sdata
20000000 D counter
20000004 D _edata
20000004 B _sbss
20000004 B samples
20000108 B _ebss
2000ff00 R _estack
2000ff00 B _snoinit
2000ff00 B g_diag
2000fff4 B _enoinit
== program headers ==
Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align
LOAD 0x010000 0x08000000 0x08000000 0x0014c 0x0014c R E 0x10000
LOAD 0x020000 0x20000000 0x0800014c 0x00004 0x00108 RW 0x10000
LOAD 0x00ff00 0x2000ff00 0x2000ff00 0x00000 0x000f4 RW 0x10000
fw.bin bytes: 336
== vector table words (od -A x -t x1z -N 8 fw.bin) ==
000000 00 ff 00 20 09 00 00 08 >... ....<
== what happens if Diag outgrows the region ==
/usr/lib/gcc/arm-none-eabi/14.2.1/../../../arm-none-eabi/bin/ld: fw_big.elf section `.noinit' will not fit in region `NOINIT'
/usr/lib/gcc/arm-none-eabi/14.2.1/../../../arm-none-eabi/bin/ld: noinit region overflow
/usr/lib/gcc/arm-none-eabi/14.2.1/../../../arm-none-eabi/bin/ld: region `NOINIT' overflowed by 60 bytes
How to read it. In the section table, Flg shows the section's flags (A: occupies memory at run time, X: executable, W: writable), Al is its alignment in bytes, Off is its position in the ELF file, and Type NOBITS means the section takes memory at run time but no bytes in the file. In the program-header table, each LOAD entry is a block the loader or flasher places in memory: FileSiz is how many bytes come from the file, MemSiz is how many bytes it occupies once loaded, and PhysAddr is where the bytes are stored (load address) while VirtAddr is where the program uses them (run address).
- Against the script:
.isr_vectorand.textcome first inFLASH(0x08000000, then0x08000008, the.rodatatable at0x0800013cis inside.text), because the script collects*(.rodata*)there..datais a RAM section with a flash load address, so the secondLOADhasVirtAddr0x20000000butPhysAddr0x0800014c, the value_sidata = LOADADDR(.data)exports..bssfollows.datainRAMand is folded into the sameLOADas extraMemSiz(0x108 = 4 bytes of.data+ 0x104 of.bss, with only 4 bytes in the file)..noinitis placed in theNOINITregion and markedNOLOAD, so it gets its ownLOADwith no file bytes and no flash image. .datais 4 bytes at the RAM address0x20000000, and its stored copy sits at0x0800014c(_sidata), just after the code. That is theAT > FLASHsplit..bssisNOBITS(takes no file space) and spans_sbss0x20000004to_ebss0x20000108; that is all the startup loop zeroes..noinitis alsoNOBITS, at0x2000ff00for 244 bytes (sizeof(Diag), matching the host run), entirely outside the zeroed range. The thirdLOADentry has file size 0, and the flash image (fw.bin, 336 bytes) holds only vectors, code, constants and the 4-byte.dataimage.- The first four bytes
00 ff 00 20are0x2000ff00stored little-endian (the least significant byte first, the usual byte order on Cortex-M parts and the one this build uses, so the bytes appear reversed relative to the written number): the initial stack pointer, which is_estack; the next four bytes09 00 00 08are0x08000009, the reset handler at0x08000008with its lowest bit set. On Cortex-M a vector entry's lowest bit must be 1 to mean "run in Thumb state" (the only state the core has), and the processor clears it to get the real address. - Changing
log[228]tolog[300]indiag.h(72 bytes more: applysed 's/log\[228\]/log[300]/' diag.hto a copy of the build directory'sdiag.hand run the same command with-o fw_big.elf) fails the link with ld's message that region NOINIT overflowed by 60 bytes (ld writes it with a backtick and a closing straight quote, as in the listing above) and with the script's own assertion (the listing keeps the three ld lines; gcc then adds a finalcollect2: error: ld returned 1 exit statusline, and the path in front of each ld line depends on the installation), so growth cannot silently overlap the stack or the next region.
Static versus dynamic linkage. A bare-metal image is linked statically: the linker resolves every symbol to a fixed address when it builds the single image above, and there is no operating-system loader to relocate it later, so nothing about those addresses can change at run time (a dynamically linked program, by contrast, gets its addresses from a loader at start-up). That is why the buffer's address can be a constant in the script, and why a bootloader and application can agree on it by sharing the same MEMORY entry.
Show in C how you would declare a callback type and keep several callbacks in a table that a driver walks. Why are function pointer tables common in firmware, and what can go wrong when the table or a target lives in a different memory region?
Sample Answer
Declaring the callback type and the table. A function pointer type is named once with typedef, and a callback almost always carries a void *ctx (context pointer) so one function can serve several instances without globals. A table entry pairs the two. The declaration typedef void (*event_cb_t)(event_t ev, void *ctx); reads from the inside out: event_cb_t is a pointer (*) to a function that takes an event_t and a void * and returns void. After the typedef, event_cb_t is just a type name, so a field or parameter can be declared as event_cb_t cb; instead of repeating that syntax.
// callbacks.h
#ifndef CALLBACKS_H
#define CALLBACKS_H
#include <stddef.h>
#include <stdint.h>
typedef enum { EV_TX_DONE, EV_RX_BYTE, EV_ERROR, EV_COUNT } event_t;
/* One callback type: the event, plus a context pointer chosen at registration. */
typedef void (*event_cb_t)(event_t ev, void *ctx);
typedef struct {
event_cb_t cb;
void *ctx;
} handler_t;
#endif /* CALLBACKS_H */
The driver keeps a table indexed by event number and walks it through one dispatch function that checks the index and the entry before calling:
// driver.c
#include <stdio.h>
#include "callbacks.h"
static void on_tx_done(event_t ev, void *ctx) { (void)ev; printf("tx done on %s\n", (const char *)ctx); }
static void on_rx_byte(event_t ev, void *ctx) { (void)ev; printf("rx byte, count so far %d\n", ++*(int *)ctx); }
static void on_error(event_t ev, void *ctx) { (void)ev; (void)ctx; puts("error event"); }
static int rx_count;
/* const table: the linker places it in read-only data, which is flash on a microcontroller */
static const handler_t g_handlers[EV_COUNT] = {
[EV_TX_DONE] = { on_tx_done, "uart0" },
[EV_RX_BYTE] = { on_rx_byte, &rx_count },
[EV_ERROR] = { on_error, NULL },
};
/* The driver's dispatch: bounds check, NULL check, then call. */
void driver_dispatch(event_t ev) {
if ((unsigned)ev >= EV_COUNT) return;
if (g_handlers[ev].cb == NULL) return;
g_handlers[ev].cb(ev, g_handlers[ev].ctx);
}
int main(void) {
driver_dispatch(EV_TX_DONE);
driver_dispatch(EV_RX_BYTE);
driver_dispatch(EV_RX_BYTE);
driver_dispatch(EV_ERROR);
driver_dispatch((event_t)7); /* out of range: ignored */
return 0;
}
Run in a gcc:14 container (GCC 14.4, aarch64, compiled with -O2 -Wall -Wextra -fsanitize=address,undefined), it prints:
tx done on uart0
rx byte, count so far 1
rx byte, count so far 2
error event
The out-of-range event 7 prints nothing: the bounds check ignored it. Using designated initialisers ([EV_ERROR] = {...}) ties each entry to its enumerator, so reordering the enum cannot silently shift the handlers, and any event left out is a zeroed entry that the NULL check skips.
Why firmware uses function pointer tables.
- Decoupling: the driver knows only the type
event_cb_t; the application supplies the behaviour, so the driver compiles and tests without it. - Compact dispatch: indexing a table replaces a long
switchorifchain with one load and one indirect call, and the table is easy to extend. State machines use a table of (state, event) to handler for the same reason. - Flash residency: a
static consttable is placed in read-only data. Compiled for Cortex-M3 witharm-none-eabi-gcc 14.2.1 -Os -c,g_handlerscame out as a 24-byte object in.rodata(three entries of 8 bytes: a 4-byte function pointer and a 4-byte context pointer), with nothing in.data. On a typical microcontroller.rodatastays in flash, so the table uses no RAM and ordinary stores cannot overwrite it. A non-const table would be in.data: a copy in RAM (the startup code copies it from flash beforemain), where a stray write to it becomes a jump to a wrong address. - The processor's own vector table (the array of handler addresses the hardware reads on an interrupt) is the same idea.
What can go wrong when the table or a target lives in a different memory region.
- The pointer must be a real function pointer, not a rebuilt address. Cortex-M cores run only Thumb code, and the address of a Thumb function carries a 1 in bit 0 as a mode marker. The compiler and linker set it when you take
&func. If you compute a code address yourself (arithmetic on a linker symbol, an address read from a flash header, a value cleared with& ~1), you must set bit 0 again. Why: the Cortex-M3 can execute only Thumb instructions (the compact instruction encoding it implements; classic ARM cores also have a wider "ARM state" encoding). A branch to an address whose bit 0 is 1 means "stay in Thumb state". A branch to an address with bit 0 equal to 0 asks the processor to switch to ARM state, which this core does not have, so it raises a fault instead of executing anything. A bare-metal program (code with no operating system, running directly on the hardware) run under QEMU (qemu-system-arm -M lm3s6965evb, an emulator with a Cortex-M3 model) shows it. It prints a function pointer's value, calls through it, then clears bit 0 and calls again:
// fp.c
#include <stdint.h>
#define UART0_DR (*(volatile uint32_t *)0x4000C000u)
#define CFSR (*(volatile uint32_t *)0xE000ED28u)
typedef void (*fn_t)(void);
static void put(const char *s) { while (*s) UART0_DR = (uint8_t)*s++; }
static void put_hex(uint32_t v) {
for (int i = 28; i >= 0; i -= 4) UART0_DR = "0123456789abcdef"[(v >> i) & 0xF];
}
static void hello(void) { put("hello called\n"); }
/* Volatile so the compiler cannot fold the address arithmetic away. */
volatile uintptr_t g_addr;
void hard_fault_c(void) {
put("HardFault, CFSR = 0x"); put_hex(CFSR); put("\n");
for (;;) { }
}
int main(void) {
put("function pointer value: 0x"); put_hex((uint32_t)(uintptr_t)hello); put("\n");
g_addr = (uintptr_t)hello;
((fn_t)g_addr)(); /* pointer as the compiler made it: bit 0 set */
g_addr = (uintptr_t)hello & ~(uintptr_t)1u;
put("calling with bit 0 cleared\n");
((fn_t)g_addr)(); /* hand-built address without the Thumb bit */
put("not reached\n");
for (;;) { }
}
extern uint32_t _estack;
void reset(void) { main(); for (;;) { } }
__attribute__((naked)) void hard_fault(void) { __asm volatile("b hard_fault_c"); }
__attribute__((section(".vectors"), used))
const void *const vectors[] = {
&_estack, reset, 0, hard_fault,
};
Reading the program:
UART0_DRis a memory-mapped register: a hardware register that appears at a fixed address (0x4000C000, the data register of the board's first serial port), so writing a byte there sends it out. The cast to avolatilepointer tells the compiler every access matters and must not be removed or reordered, which is what stops it optimising the writes away.CFSRis the same trick for the Configurable Fault Status Register at0xE000ED28.putsends a string a byte at a time.put_hexprints a 32-bit value as eight hex digits: it shifts the value right by 28, 24, ... 0 bits, masks the low 4 bits with& 0xFand uses the result to index the digit string.mainprints the address ofhello, calls it through thevolatilevariableg_addr(so the compiler cannot work out the target at build time), then clears bit 0 of the address (& ~1) and calls it again.- The last array is the vector table (the table of addresses the processor reads at reset and on every exception): entry 0 is the initial stack pointer, entry 1 the reset handler (where execution starts), entry 3 the HardFault handler. The attribute puts it in a section called
.vectors, which the linker script places at address 0.resetsimply callsmain.hard_faultis declarednaked, meaning the compiler writes no prologue or epilogue, so its only instruction is a branch to the normal C functionhard_fault_c. - The linker script (given to
-T) tells the linker where memory is. The one used here:
MEMORY { FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 256K
RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 64K }
_estack = ORIGIN(RAM) + LENGTH(RAM);
SECTIONS {
.text : { KEEP(*(.vectors)) *(.text*) *(.rodata*) } > FLASH
.bss : { *(.bss*) *(COMMON) } > RAM
}
_estack is a linker symbol, a name whose value the linker computes (here the top of RAM) and that C code can refer to as extern uint32_t _estack;. The .vectors section comes first in .text, so it lands at address 0.
Built with arm-none-eabi-gcc -mcpu=cortex-m3 -mthumb -Os -nostdlib -T link.ld fp.c -o fp.elf and run with qemu-system-arm -M lm3s6965evb -kernel fp.elf -nographic, it prints (with -nographic the board's first serial port already goes to the terminal; adding -serial stdio as well fails with cannot use stdio by multiple character devices, so write it as -serial stdio -monitor none if you want it explicit; the program ends in an endless loop, so stop QEMU with Ctrl-A then X):
function pointer value: 0x00000025
hello called
calling with bit 0 cleared
HardFault, CFSR = 0x00020000
The value 0x25 is odd, so bit 0 is set. The call with bit 0 cleared lands in the HardFault handler (the processor's catch-all fault exception), and the CFSR (Configurable Fault Status Register) reads 0x00020000: bit 17, which CMSIS defines as SCB_CFSR_INVSTATE ("invalid state": an attempt to execute in an instruction set state the core does not support), per core_cm3.h in ARM-software/CMSIS_6. The 0x00020000 is 1 << 17, so only that one bit is set. This is why tables of code addresses must hold values the compiler produced. A bootloader that jumps to an application's reset handler should use the address stored in the application's vector table, which the linker already built with the bit set, and not a number it derives from a linker symbol.
Further pitfalls.
- RAM-resident tables and code need initialising first. A table in
.data(or code placed in RAM for speed) holds garbage or zeros until the startup code has copied it from flash. A callback fired by an interrupt before that copy finishes, or by an early constructor, jumps through an unset entry. Enable interrupts only after startup finishes, and keep the dispatch NULL check as the last defence. - The table and its targets can be different builds. If a bootloader holds a table that points into an application image, the pointers are valid only for that exact image. After an update, a stale table calls into the middle of different code. Version the table (a magic number and layout version at its head) and validate that each pointer lies inside the application's code range before calling it.
- Calls through a table are hard for tools to follow. Static stack analysis cannot know the target of an indirect call, so the worst-case stack depth through a callback needs a manual bound, and a corrupted pointer fails at runtime, not at link time.
- Context lifetime. The
ctxpointer must outlive the registration; a pointer to a stack variable that has returned is a classic bug, and a context shared with an interrupt needs the same protection as any other data shared with an interrupt.
Write a bounded string copy for firmware that never overruns its destination, always terminates the result and tells the caller whether it truncated. What undefined behaviour does it avoid, and why is it suitable for a constrained target?
Sample Answer
The function. Three rules drive the design: write at most dst_size bytes, write a terminating '\0' (the zero byte that marks the end of a C string) whenever dst_size is at least 1, and return a flag the caller cannot confuse with a length. The full program below is the function plus a test driver that copies into heap blocks of exactly the stated capacity (a 1-byte block for capacity 0, where nothing may be written), so AddressSanitizer (a compiler-inserted checker that aborts on any out-of-bounds access) would stop the run at the first stray byte.
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Copies src into dst (capacity dst_size bytes, including the terminator).
Always terminates when dst_size > 0. Returns true if src did not fit. */
bool str_copy(char *dst, size_t dst_size, const char *src)
{
if (dst_size == 0) {
return true; /* no room even for '\0': nothing written */
}
size_t i = 0;
while (i < dst_size - 1 && src[i] != '\0') {
dst[i] = src[i];
i++;
}
dst[i] = '\0';
return src[i] != '\0'; /* stopped early because dst was full */
}
static void try_copy(const char *src, size_t cap)
{
/* heap block of exactly cap bytes: AddressSanitizer flags any write past it */
char *buf = malloc(cap ? cap : 1);
if (!buf) { return; }
memset(buf, 'x', cap ? cap : 1);
bool trunc = str_copy(buf, cap, src);
if (cap > 0) {
printf("cap=%zu src=\"%s\" -> \"%s\" truncated=%d\n", cap, src, buf, trunc);
} else {
printf("cap=%zu src=\"%s\" -> untouched('%c') truncated=%d\n", cap, src, buf[0], trunc);
}
free(buf);
}
int main(void)
{
try_copy("UART1", 16); /* fits with room to spare */
try_copy("UART1", 6); /* exact fit: 5 chars + terminator */
try_copy("UART1", 5); /* one byte short */
try_copy("UART1", 1); /* only room for the terminator */
try_copy("UART1", 0); /* no room at all */
try_copy("", 4); /* empty source */
return 0;
}
Compiled with gcc -O2 -Wall -Wextra -fsanitize=address,undefined in a gcc:14 container (GCC 14.4, aarch64), it ran clean and printed:
cap=16 src="UART1" -> "UART1" truncated=0
cap=6 src="UART1" -> "UART1" truncated=0
cap=5 src="UART1" -> "UART" truncated=1
cap=1 src="UART1" -> "" truncated=1
cap=0 src="UART1" -> untouched('x') truncated=1
cap=4 src="" -> "" truncated=0
The boundary cases matter most. cap=6 is an exact fit: five characters plus the terminator, so nothing is lost. cap=5 loses one character but is still a valid, terminated string. cap=0 is guarded before the loop because dst_size - 1 on an unsigned size_t (the unsigned type for sizes) would wrap around to a huge number and turn a bound into no bound. Unsigned arithmetic has no negative numbers: it wraps modulo 2^N, so with size_t size = 0;, size - 1 is the largest value the type holds. On the 64-bit host used here printf("%zu\n", size - 1) prints 18446744073709551615; on a 32-bit Cortex-M it is 4294967295. The loop test i < dst_size - 1 would then be true for every i, and the copy would run until it hit the end of src. With no room for even the terminator, the function writes nothing and reports truncation.
Why not strncpy. strncpy(dst, src, n) is the standard-library call people reach for, and it fails the second rule: when src has n or more characters it copies exactly n and writes no terminator. The following program, built with the same flags, copies five characters into a 5-byte block and then prints the result as a string:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char *buf = malloc(5); /* a 5-byte block */
strncpy(buf, "UART1", 5); /* copies 5 chars, writes no '\0' */
puts(buf); /* scans for a '\0' past the block */
free(buf);
return 0;
}
The run aborts with ERROR: AddressSanitizer: heap-buffer-overflow ... READ of size 6, followed by the line located 0 bytes after 5-byte region. Read it as: puts needs the string's length, so it scans from the start of the block looking for a '\0'. The five bytes UART1 contain none, so the scan examined a sixth byte, the one immediately after the block, and the checker reports a 6-byte read that ends outside the 5-byte allocation. On a real device nothing would stop that scan; it would keep reading whatever bytes follow until it happens on a zero. strncpy also pads the rest of the destination with zero bytes, so copying a short name into a 256-byte buffer writes all 256 bytes, which wastes cycles on a small core. strcpy has no bound at all.
Undefined behaviour avoided. Undefined behaviour (UB) means the C standard places no requirements on what the program does, so the compiler may assume it never happens. The function prevents these cases:
- Writing outside
dst(an out-of-bounds write): the loop conditioni < dst_size - 1caps the writes, and the terminator goes to indexi, which is at mostdst_size - 1. - Later reading an unterminated array as a string (the
strncpycase above): the terminator is always written. - The
dst_size == 0wrap-around described above. Unsigned wrap-around is well defined in C, so the subtraction is not itself undefined behaviour; what the guard prevents is the unbounded loop it would cause, whose writes pastdstare undefined behaviour. - Reading
srcbeyond its own terminator: the loop stops atsrc[i] == '\0', and the truncation test reads onlysrc[i], the byte the loop stopped on. It never callsstrlenonsrc, so it reads at mostdst_sizebytes ofsrc.
Preconditions it cannot enforce. src must be a valid terminated string, dst must really have dst_size bytes, and the two must not overlap. Pass sizeof buf for an array, never sizeof a pointer parameter, which is the size of the pointer (commonly 4 bytes on a Cortex-M). A NULL argument is also the caller's bug here, and a firmware team may prefer an assertion in debug builds over a silent check.
Why it suits a constrained target. It uses no heap (the dynamic allocator that small devices often omit), no static buffer, and no library call, so it is reentrant (safe to call again while another call is already in progress, for example from an interrupt that preempts the main loop, because it keeps its state only in its own local variables and arguments): an interrupt handler and the main loop can use it on different buffers at once. It makes one forward pass and touches only the bytes it copies plus one terminator, so its worst-case time is bounded by dst_size, which is the figure a real-time budget needs. It is small enough to inline, and the truncation flag lets the caller choose the policy: log and drop a command that does not fit, or accept a clipped display label, instead of letting a clipped device name silently match the wrong entry. One caveat: cutting at a byte boundary can split a multi-byte UTF-8 character, so text for a display needs a character-aware cut. The function is not a standard one (strlcpy exists on BSD systems but is not part of ISO C), so a firmware project defines its own and tests it, as above.
Could a compacting allocator make sense on a 64 KB microcontroller with no MMU? Describe how it would work, how pointers stay valid, what pause times to expect, and when you would rather use a simpler non-moving allocator.
Sample Answer
Can it make sense? Yes, with handles, in one narrow situation. A compacting allocator slides live blocks together to turn many small free holes into one large one. Without an MMU (memory management unit, the hardware that remaps addresses) nothing can quietly remap memory, so every pointer to a moved block would break. The only workable design is to never hand out raw pointers: the caller holds a handle, a small index into a table the allocator owns, and the table stores the block's current address. Moving a block means a memmove (like memcpy, but defined for source and destination that overlap, which happens when a block slides down by less than its own length) plus one table update, and no caller notices.
How it works. Run in a gcc:14 container (GCC 14.4, aarch64, with -O2 -Wall -Wextra -fsanitize=address,undefined), this handle heap uses a 32 KB arena, a table of 128 entries (offset, size, lock count) and a bump pointer (a single variable, top, marking the end of the used area; a new block is carved from it by advancing it):
#ifndef HANDLE_HEAP_H
#define HANDLE_HEAP_H
#include <stddef.h>
#include <stdint.h>
typedef int16_t handle_t; /* index into the handle table, -1 = failure */
void hh_init(void);
handle_t hh_alloc(size_t size); /* -1 if no contiguous space even after compaction */
void hh_free(handle_t h);
void *hh_lock(handle_t h); /* pointer valid until hh_unlock; block cannot move */
void hh_unlock(handle_t h);
size_t hh_compact(void); /* returns bytes moved; a locked block stays put, blocks above it still slide down to it */
size_t hh_largest_hole(void); /* largest free gap anywhere in the arena; only the gap above the last block is usable without compacting */
size_t hh_free_total(void);
#endif
#include <string.h>
#include "handle_heap.h"
#define ARENA_SIZE 32768u
#define MAX_HANDLES 128u
#define ALIGN 4u
typedef struct {
uint16_t offset; /* where the block starts in the arena */
uint16_t size; /* rounded size; 0 = handle unused */
uint8_t locks; /* >0: the block must not move */
} entry_t;
static uint8_t arena[ARENA_SIZE] __attribute__((aligned(4)));
static entry_t table[MAX_HANDLES];
static uint16_t top; /* end of the highest block: bump pointer */
void hh_init(void) { memset(table, 0, sizeof table); top = 0; }
static size_t round_up(size_t n) { return (n + ALIGN - 1u) & ~(size_t)(ALIGN - 1u); }
/* Blocks stay ordered by offset because every allocation goes on top and compaction keeps order. */
static int next_block(int after, int *out) { /* the handle of the lowest block above 'after' offset */
int best = -1;
for (unsigned h = 0; h < MAX_HANDLES; h++)
if (table[h].size && (after < 0 || table[h].offset > table[after].offset) &&
(best < 0 || table[h].offset < table[best].offset)) best = (int)h;
*out = best;
return best >= 0;
}
size_t hh_free_total(void) {
size_t used = 0;
for (unsigned h = 0; h < MAX_HANDLES; h++) used += table[h].size;
return ARENA_SIZE - used;
}
size_t hh_largest_hole(void) {
size_t best = 0, prev_end = 0;
int h = -1;
while (next_block(h, &h)) {
size_t gap = table[h].offset - prev_end;
if (gap > best) best = gap;
prev_end = (size_t)table[h].offset + table[h].size;
}
return ARENA_SIZE - prev_end > best ? ARENA_SIZE - prev_end : best;
}
size_t hh_compact(void) {
size_t moved = 0, dst = 0;
int h = -1;
while (next_block(h, &h)) {
if (table[h].offset != dst) {
if (table[h].locks) { dst = (size_t)table[h].offset + table[h].size; continue; }
memmove(&arena[dst], &arena[table[h].offset], table[h].size);
table[h].offset = (uint16_t)dst;
moved += table[h].size;
}
dst += table[h].size;
}
top = (uint16_t)dst;
return moved;
}
static int try_alloc(size_t n, handle_t *out) {
for (unsigned h = 0; h < MAX_HANDLES; h++) {
if (table[h].size == 0) {
if ((size_t)top + n > ARENA_SIZE) return 0;
table[h].offset = top; table[h].size = (uint16_t)n; table[h].locks = 0;
top = (uint16_t)(top + n);
*out = (handle_t)h;
return 1;
}
}
return 0;
}
handle_t hh_alloc(size_t size) {
size_t n = round_up(size ? size : 1u);
handle_t h;
if (try_alloc(n, &h)) return h;
hh_compact(); /* pause happens here, only when needed */
return try_alloc(n, &h) ? h : (handle_t)-1;
}
void hh_free(handle_t h) {
if (h < 0 || (unsigned)h >= MAX_HANDLES) return;
table[h].size = 0;
/* If it was the top block, lower the bump pointer so the space is reusable at once. */
size_t end = 0; int b = -1;
while (next_block(b, &b)) end = (size_t)table[b].offset + table[b].size;
top = (uint16_t)end;
}
void *hh_lock(handle_t h) { table[h].locks++; return &arena[table[h].offset]; }
void hh_unlock(handle_t h) { if (table[h].locks) table[h].locks--; }
Reading the code. next_block(after, &out) finds the block that comes next in memory: it scans the whole table for the used entry (size non-zero) with the smallest offset that is above the offset of block after (or the smallest of all when after is -1), and returns its handle; calling it in a loop visits the blocks in address order. A full scan per step is slow for a large table but fine for 128 entries and keeps the code tiny. hh_largest_hole walks the blocks in order and measures the gap between the end of the previous block and the start of the next, plus the space above the last block. Only that last space can be used by an allocation without compaction, because try_alloc always carves a new block at top; a gap lower down is reachable only after hh_compact has closed it, so the function measures fragmentation rather than what the next allocation can get. hh_compact keeps a destination offset dst: a block that is not at dst and not locked is memmoved down to dst and its table offset updated; a locked block stays where it is and dst jumps to its end, so the blocks above it still compact against it. hh_free clears the entry's size and then recomputes top as the end of the highest remaining block, so freeing the top block makes that space available to the bump pointer at once.
How pointers stay valid. The caller gets a pointer only by calling hh_lock(h), uses it, then calls hh_unlock(h). A block with a non-zero lock count is never moved. Rules that make this safe: do not keep the pointer after unlocking; do not lock across a blocking call or a task switch unless you accept that compaction is held off; and if an interrupt handler or DMA (direct memory access, a peripheral writing to memory without the CPU) uses a block, that block stays locked for as long as the hardware can touch it.
Behaviour. A driver that creates 16 blocks of 2000 bytes, frees every other one, compacts, and later asks for more than any single hole:
#include <stdio.h>
#include <string.h>
#include "handle_heap.h"
int main(void) {
hh_init();
handle_t h[16];
/* 16 blocks of 2000 bytes = 32000 of the 32768-byte arena, each filled with its own tag. */
for (int i = 0; i < 16; i++) {
h[i] = hh_alloc(2000);
memset(hh_lock(h[i]), 'A' + i, 2000);
hh_unlock(h[i]);
}
printf("after 16 allocs: free total %zu, largest hole %zu\n", hh_free_total(), hh_largest_hole());
for (int i = 1; i < 16; i += 2) hh_free(h[i]); /* free every other block */
printf("after freeing 8 alternate blocks: free total %zu, largest hole %zu\n",
hh_free_total(), hh_largest_hole());
size_t moved = hh_compact();
printf("compact moved %zu bytes; largest hole now %zu\n", moved, hh_largest_hole());
int ok = 1; /* pointers fetched through handles still see the right data */
for (int i = 0; i < 16; i += 2) {
unsigned char *p = hh_lock(h[i]);
for (int k = 0; k < 2000; k++) if (p[k] != 'A' + i) ok = 0;
hh_unlock(h[i]);
}
printf("data intact after move: %s\n", ok ? "yes" : "NO");
/* Fill the space again, free alternate blocks, then ask for more than any single hole. */
handle_t n[8];
for (int i = 0; i < 8; i++) n[i] = hh_alloc(2000);
for (int i = 1; i < 8; i += 2) hh_free(n[i]);
printf("before big alloc: free total %zu, largest hole %zu\n", hh_free_total(), hh_largest_hole());
handle_t big = hh_alloc(6000);
printf("alloc 6000: %s (compaction ran inside hh_alloc)\n", big >= 0 ? "ok" : "failed");
/* A locked block stays put, so the hole below it cannot be closed. */
hh_free(big);
hh_free(h[2]);
hh_lock(h[4]);
size_t before = hh_largest_hole();
size_t moved2 = hh_compact();
printf("h[4] locked: largest hole %zu before, %zu after compact (moved %zu bytes)\n",
before, hh_largest_hole(), moved2);
hh_unlock(h[4]);
moved2 = hh_compact();
printf("h[4] unlocked: compact moved %zu bytes, largest hole %zu\n", moved2, hh_largest_hole());
return 0;
}
prints:
after 16 allocs: free total 768, largest hole 768
after freeing 8 alternate blocks: free total 16768, largest hole 2768
compact moved 14000 bytes; largest hole now 16768
data intact after move: yes
before big alloc: free total 8768, largest hole 2768
alloc 6000: ok (compaction ran inside hh_alloc)
h[4] locked: largest hole 8768 before, 8768 after compact (moved 0 bytes)
h[4] unlocked: compact moved 20000 bytes, largest hole 10768
After freeing alternate blocks, 16768 bytes are free but the largest single hole is 2768 bytes (the 768 never-used bytes plus the 2000 just freed at the top) and every other hole is 2000 bytes, so no request above 2768 bytes can be served without compaction (fragmentation). Eight blocks survive (h[0], h[2], ..., h[14]). h[0] is already at offset 0 and does not move; the other seven slide down, 7 x 2000 = 14000 bytes, and the largest hole becomes the whole 16768 (32768 - 8 x 2000). The tag check shows that every block's contents survived the move. The last two lines come from this state: after the large allocation succeeded, 12 blocks besides the 6000-byte one are live in the lower part of the arena (the eight survivors h[0], h[2], ..., h[14] and the four 2000-byte survivors of the second batch); the 6000-byte block and h[2] are then freed, leaving 11. Freeing h[2] leaves a 2000-byte gap at offset 2000, below ten blocks (six more from the first batch and the four from the second). With h[4] locked, compaction moved nothing: the block just above the gap cannot move, so everything above it is already contiguous, and the 2000-byte gap stayed. After unlocking, all ten blocks above the gap slide down by 2000 bytes each: 10 x 2000 = 20000 bytes moved, and the free space becomes one hole of 32768 - 22000 = 10768 bytes.
Pause time to expect. The pause has two parts. The copy part is proportional to the bytes moved, because each moved byte is read and written once; the worst case is moving every live byte, so it is roughly bytes_moved x cycles_per_byte / clock. As an ESTIMATE (the cycles-per-byte figure is an assumption, to be replaced by a measurement on the target): at a cautious 4 cycles per byte and a 48 MHz clock, copying the 20,000 bytes of the demo takes 20000 x 4 / 48e6 = 1.7 ms, and copying a full 32 KB arena takes 32768 x 4 / 48e6 = 2.7 ms.
The second part is the table walk, and in this code it is not small. next_block rescans all 128 table entries for every block it visits, so one compaction with 128 live blocks makes 129 x 128 = 16,512 passes through that scan loop even when it moves 0 bytes (counted by instrumenting the loop in the host build), and each hh_free repeats a similar walk (16,384 passes with 127 blocks left live). A pass over a used entry is between 11 and 20 Thumb-2 instructions depending on the path through the loop in the arm-none-eabi-gcc 14.2.1 -mcpu=cortex-m3 -mthumb -O2 listing (counted by hand), so as an ESTIMATE the walk alone is roughly 180,000 to 330,000 instructions (16,512 x 11 and 16,512 x 20), about 4 to 7 ms at 48 MHz if each instruction took one cycle, more than the 2.7 ms needed to copy the whole arena. With only 16 live blocks, as in the demo, it is about 2,000 passes and matters much less. If the table must be large, keep the blocks in an address-ordered linked list (a next index in each entry) so compaction and free visit each live block once instead of rescanning the table. During that time interrupts are not necessarily masked, but any task that needs the heap waits, and any locked block constrains the result. Measure it on the target with the cycle counter or a GPIO pin and a scope, for the worst fragmentation pattern your product can produce.
Two ways to bound the pause: compact incrementally (move one block, or up to N bytes, per call from the idle task, so each step costs about block_size x cycles_per_byte / clock plus one table scan; for a 2000-byte block under the same assumptions the copy is 2000 x 4 / 48e6, about 0.17 ms), or compact only at a known quiet point such as between frames or after a mode change.
Costs besides the pause. The handle table costs RAM (the demo's entry is 6 bytes after padding, so 128 handles take 768 bytes, about 2.3% of a 32 KB arena), and every access goes through a lookup and a lock/unlock pair. Code gets harder to write correctly: a forgotten hh_unlock pins that block in place for good, so the holes below it can never be closed, and a pointer kept past hh_unlock becomes a wild pointer after the next compaction, with no compiler warning.
When to use a simpler non-moving allocator. Prefer fixed-size pools (one pool per object size, O(1) alloc and free, no fragmentation inside a pool) whenever the set of object sizes is small and known, which is the usual case in firmware. Prefer a segregated-fit allocator (separate free lists for different size classes, so a request goes straight to the right list) or a buddy allocator when sizes vary but a hard bound on allocation time matters more than the last byte. Choose compaction only when all of these hold: sizes are varied and not predictable (for example variable-length audio or network buffers), RAM is too tight to waste on pool slack, blocks are created and destroyed continuously so fragmentation is real, and there is a point in the schedule where a pause of a millisecond or two is acceptable. For a control loop with a hard deadline, the compaction pause is the deciding factor against it.
A shipped device uses malloc and free freely and starts failing allocations after weeks of uptime. How would you migrate it to a safer allocation scheme with minimal code churn, and how do you de-risk the rollout on devices in the field?
Sample Answer
Recommendation. Do not rewrite every call site in one release. Put a thin layer under the existing malloc/free calls first, measure what the fleet really allocates, then move call sites to static buffers or pools in order of payoff, always with the old heap still compiled in as a fallback. Ship each step behind a switch the field can flip back. Allocations that fail only after weeks (typically because the heap's free space has broken into many small pieces, called fragmentation, none big enough for a new request) mean the rollout must be judged by leading indicators (pool misses, and the largest free hole: the biggest single contiguous block of free memory the legacy heap could still hand out), not by waiting for a crash.
Step 1: add a shim, change no callers. The GNU linker option -Wl,--wrap=malloc redirects every undefined reference to malloc in the objects being linked to __wrap_malloc, and __real_malloc still reaches the original. Concretely, the linker rewrites a call in the application's object file as follows: p = malloc(7); is resolved as p = __wrap_malloc(7);, and inside __wrap_malloc the call __real_malloc(n) is resolved to the library's own malloc. No source line in the callers changes. Repeat for free, calloc and realloc, because wrapping only some of them lets a block from one allocator reach the other's free. The shim below serves small requests from pools, counts every miss, and sends misses to the legacy heap, so a wrongly sized pool degrades to the old behaviour instead of failing. Its free tells the two apart by address range:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
/* ---- migration layer: every existing malloc/free call lands here without editing the callers ---- */
void *__real_malloc(size_t n);
void __real_free(void *p);
static unsigned live, peak, fallbacks;
static uint8_t pool_mem[4][64];
static uint8_t pool_used[4];
void *__wrap_malloc(size_t n) {
if (n <= 64)
for (unsigned i = 0; i < 4; i++)
if (!pool_used[i]) { pool_used[i] = 1; if (++live > peak) peak = live; return pool_mem[i]; }
fallbacks++; /* pool miss: count it, then use the legacy heap */
return __real_malloc(n);
}
void __wrap_free(void *p) {
uintptr_t off = (uintptr_t)p - (uintptr_t)pool_mem;
if ((uintptr_t)p >= (uintptr_t)pool_mem && off < sizeof pool_mem) { /* ours: return it to the pool */
pool_used[off / 64] = 0; live--; return;
}
__real_free(p); /* anything else came from the real heap */
}
/* ---- legacy application code, unchanged ---- */
char *make_name(const char *s) { char *p = malloc(strlen(s) + 1); if (p) strcpy(p, s); return p; }
int main(void) {
char *a = make_name("sensor"), *b = make_name("actuator");
printf("a=%s b=%s live=%u peak=%u\n", a, b, live, peak);
free(a); free(b);
char *big = make_name("this name is deliberately longer than sixty-four bytes so the pool must refuse it");
printf("long name served: %s, legacy-heap fallbacks=%u, pool live=%u\n", big ? "yes" : "no", fallbacks, live);
free(big);
char *d = strdup("from libc"); /* allocated inside libc, not by our object file */
printf("strdup block went through the pool: %s (live=%u)\n", live ? "yes" : "no", live);
free(d);
return 0;
}
Built with gcc -O2 -Wall -Wextra -fsanitize=address,undefined -Wl,--wrap=malloc -Wl,--wrap=free in a gcc:14 container (GCC 14.4, aarch64) with no warnings, and run, it printed:
a=sensor b=actuator live=2 peak=2
long name served: yes, legacy-heap fallbacks=1, pool live=0
strdup block went through the pool: no (live=0)
Tracing the program: make_name("sensor") calls malloc(7) (6 characters plus the terminator), which __wrap_malloc serves from pool block 0 (live=1); make_name("actuator") calls malloc(9) and gets block 1 (live=2, peak=2). free(a) reaches __wrap_free, whose address test says the pointer lies inside pool_mem, so block 0 is marked unused (live=1), and free(b) does the same for block 1 (live=0). The long name needs 82 bytes, more than the 64-byte blocks, so __wrap_malloc counts a fallback and calls __real_malloc; its free falls outside the pool range and goes to __real_free. Two things to read there. The unchanged legacy function make_name was served by the pool for short names and by the legacy heap for the long one, with the fallback counted. And the block allocated inside libc by strdup did not pass through the shim in this host build, because glibc is a shared library here: its internal call to malloc is resolved by the dynamic loader when the program starts, after --wrap has finished rewriting the references the linker saw. The outcome depends on how the library is linked, so do not generalise from this run. --wrap rewrites undefined references in every input file the linker reads, archive members included: linking the same program with -static makes the strdup inside libc.a call __wrap_malloc, and the pool then serves that block. A bare-metal newlib build differs again: newlib's strdup calls the reentrant _strdup_r, which calls _malloc_r rather than malloc (seen by disassembling an image linked with GNU Arm Embedded 14.2.1), so --wrap=malloc alone misses it; adding --wrap=_malloc_r redirected that call in the same disassembly, and the matching reentrant free, calloc and realloc functions need the same treatment. Either way, check each library with the map file, nm or objdump on the real target before trusting the counts. The shim as written is not safe for concurrent callers; on a device add a critical section or a lock around the pool bookkeeping.
Step 2: learn the workload (one release in shadow mode). Shadow mode means the new layer runs and records what it would do while the old behaviour stays in charge. Here the shim still hands everything to the legacy heap but records a size histogram (how many requests fall into each size range, for example 1 to 16 bytes, 17 to 32 bytes and so on), peak live blocks per bucket, and whether blocks are freed soon or live until reset. Send these in the existing telemetry. The data replaces guessing and tells you which pool sizes and counts to build.
Step 3: sort the call sites by lifetime and convert, cheapest first.
- Allocated once at startup and never freed: make them static arrays or
staticobjects. No allocator, no failure path, and the linker map shows the RAM cost. - Fixed-size objects created and destroyed at run time (messages, packets, timers): a fixed-size pool, one per type or size class.
- Short-lived variable-size scratch (formatting, parsing): a buffer on the stack or a reusable static buffer, sized for the worst case.
- What remains (rare, truly variable): leave on a small heap, or give it an arena (also called a region: memory handed out by bumping a pointer through one block and released all at once at the end of a transaction), so one bad call site cannot fragment everything else.
With the shim in place, each conversion is local to one call site and can be shipped separately.
Step 4: de-risk the rollout on devices in the field.
- Switch and rollback. Keep the legacy path compiled in, with a configuration flag (or a dual-image update, where the device holds two firmware images and can boot the previous one) that routes everything back to the old heap. Remove it only after a release has run clean.
- Canary. A canary release sends the new firmware to a small group of devices first, as an early warning before everyone gets it. Release first to a small slice of the fleet, picked to include the heaviest users, and compare it against the rest.
- Judge by leading indicators. Because the old failure took weeks to show, a few clean days prove little. Watch the pool-miss count, the high-water mark per pool, the largest free hole on the legacy heap, and reset and watchdog counts. A pool miss rate that is above zero means a pool is too small. Keep the canary running longer than the old time to first failure before you widen it, and in parallel replay recorded or synthetic traffic on bench units at high speed so the long-uptime pattern is exercised sooner.
- Check the RAM budget at link time. Pools reserve their memory permanently, whereas the old heap shared one region. Confirm with the map file or
sizeoutput that total RAM, stacks included, still fits, and keep a margin for the larger blocks. - Watch for hidden callers. Third-party code,
reallocon pooled blocks (which must allocate, copy and free across pools), andfreeof pointers that came from elsewhere. The address-range test above handles the last case, and a counter for "free of unknown pointer" shows the others.
What would change this plan. If the shadow-mode data shows that nearly all allocations are boot-time and never freed, skip the pools and make them static. If the shim's cost or a library that bypasses it cannot be controlled, convert the call sites directly instead of wrapping.
Unlock Full Question Bank
Get access to all Embedded C and C++ Programming interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.