Where Memory Goes

A chip has one pool of RAM, and the stack, the heap and your globals share it. Learn to measure each, fix what fragments, and make an overflow stop loudly.

Slide the call depth past 10 with protection set to None. Then try Painted and MPU guard at the same depth. Then we build it, piece by piece, from one stack frame to a fault you can read.

You need a little C (functions, arrays, pointers) and a rough idea of a byte. We build the rest from zero.

Built from primary sources: the Memfault Interrupt posts on measuring stack usage and the Cortex-M MPU, the Arm Cortex-M reference material, and the FreeRTOS and Zephyr documentation. Lesson 6 of the Firmware from Zero series.

Call deeper, watch the stack

6

A model, not a real chip. Illustrative numbers: 16 KB of RAM at 0x20000000, a 2,048 byte stack, a base frame of 64 bytes and 192 bytes for each deeper call. The MPU guard is the 64 byte region of Chapter 8.

Chapter 0

One Room, Four Tenants

See why a chip with 16 KB of RAM can run for three days and then reset with no message at all

A small sensor node sits in a greenhouse. It reads a temperature, packs a radio message and sends it. It works on your desk. In the greenhouse it resets about once every three days. There is no crash log, and nothing in the code looks wrong.

Nothing here is broken in the way a typo is broken. The program is fine at each line. The trouble is that something wrote to a byte it did not own, a long time before the reset. To find it, you must know who owns which bytes.

The room and its tenants

A microcontroller has a block of fast memory called RAM (random access memory, the working desk of the program; it forgets everything at power off). A typical small part has 16 KB to 256 KB of it. The nRF52840 has 256 KB. All of it is one flat range of addresses, and four tenants share it.

The first tenant is static data: the global and static variables. The linker (the tool that places your compiled code and data at fixed addresses, see the toolchain lesson) gives each one a fixed address. .data holds globals that start with a value. .bss holds globals that start at zero. These never move and never grow.

The second tenant is the heap: memory that the program asks for at run time with malloc and gives back with free. The third is the stack: the memory where each function call keeps its local variables and its return address. The fourth is a second kind of stack. On a Cortex-M chip, interrupt handlers run on the main stack, and an RTOS gives each task a stack of its own (the RTOS lesson builds that part).

The first tenant is fixed at link time. The other three change while the program runs. The heap usually grows toward higher addresses, and the stack grows toward lower ones. They head toward each other like two people walking along one corridor.

Here is the part that surprises people. On most small chips, nothing checks. There is no operating system to say no. The hardware lets any instruction write any RAM address. If the stack grows into the heap, the write simply succeeds.

Budget a room you cannot see

The linker knows how big .data and .bss are, so it can check that they fit. Many vendor linker scripts also reserve a minimum heap and a minimum stack and check that those reserves fit. That check is about the reserve. It cannot know the peak your code reaches at run time. Try a budget below.

Budget the 16 KB

The purple part is static data from a link map. Set how large the heap and the stack get at their peak. The bar shows whether they fit, or by how much they collide.

6,144 B
2,560 B

Illustrative: 16,384 bytes of RAM, and 4,096 bytes of static data (512 in .data, 3,584 in .bss). Real peaks are not known from the source. Chapters 2 and 3 measure the stack, and Chapter 5 measures the heap.

Move the stack peak to 4,096 and the heap to 8,192. The three add up to 16,384 bytes and fit with zero room to spare. One more call, one more message, and they meet. Because the peaks come from input data and timing, the greenhouse can hit a peak your desk never did.

The cure has three parts, and they are the three halves of this lesson. First, measure the peaks, so you know them. Second, remove the growth where you can, by giving every object a fixed place. Third, make a wrong write loud, with a hardware unit that stops it. We take them in order.

The road

  1. What a function call does: the stack frame, the stack pointer, and what an interrupt adds.
  2. Counting the stack from the code: the call graph and the worst path.
  3. Painting the stack: fill it, run it, find the high-water mark.
  4. When the stack overflows: the silent kind, and why it looks like a random bug.
  5. The heap and its fragments: free memory you cannot use.
  6. Pools and static allocation: fixed-size blocks that never fragment.
  7. The memory protection unit: regions, alignment and the two registers that set them.
  8. A guard that faults: reading the fault, and the stack limit registers.
  9. The field guide: numbers, a checklist and the core code.

Part of this lesson uses the exception stacking you meet in interrupts and DMA, and the reset sequence in reset to main(), which sets the first stack pointer. Read those first if either idea is new.

The program links without a warning, and RAM has room left over. Why can the stack still overwrite other data?

Chapter 1

What a Function Call Does

Follow one call down the stack, count its bytes, and see what an interrupt adds on top

You are reading a book and the phone rings. You put a bookmark in the page, answer, and talk. While you talk, a friend asks you to look something up, so you leave a note on top of the bookmark. When you finish each task, you take the top note off the pile and go back to what it says.

That pile of notes is the stack. Each note says where to resume. The last note you put down is the first one you pick up. A program does the same thing with function calls, and the chip does it in hardware.

The frame: one function's slice of the stack

When a function calls another one, two things must survive. The CPU must remember where to come back to. And the caller's own working values must not be spoiled. The callee saves them in a block of stack memory called a stack frame.

A frame holds three things. The first is the return address, kept in the link register LR and pushed onto the stack if the function calls others. The second is the registers the function wants to reuse, saved so it can restore them. The third is the function's local variables: the arrays and structs declared inside it.

On an Arm Cortex-M chip, a register called the stack pointer (SP) holds the address of the newest item. The stack is full descending. That means a push first subtracts from SP and then writes, so the stack grows toward lower addresses. At reset the chip loads the first SP value from word 0 of the vector table; reset to main() shows where it comes from.

A worked frame, instruction by instruction

Here is what a compiler may emit for a function that calls another and has a 20 byte local array. The numbers are a hand-made example in Thumb assembly, and SP starts at 0x20003FF0.

asmread_sensor:
    push {r4, r5, lr}      @ 3 words: SP = 0x20003FF0 - 12 = 0x20003FE4
    sub  sp, sp, #20      @ room for char buf[20]: SP = 0x20003FD0
    @ ... body, may call spi_xfer() ...
    add  sp, sp, #20      @ give the locals back: SP = 0x20003FE4
    pop  {r4, r5, pc}      @ restore r4, r5 and jump back: SP = 0x20003FF0

Count it. The push takes 3 words of 4 bytes, so 12 bytes. The local array takes 20 bytes. The frame is 32 bytes, and SP ends 32 bytes lower than it began: 0x20003FF0 minus 32 is 0x20003FD0. The final pop loads the saved LR value straight into PC, which is the return jump.

The frame size stays a multiple of 8. The Arm calling convention (the AAPCS, the rulebook for how functions pass arguments and keep registers) wants SP aligned to 8 bytes at every function call. So a compiler pads a frame when it must.

The compiler also decides how much of a frame it needs. With optimisation off, every local variable lives on the stack. With -Os, many locals live in registers, so the same function may use 24 bytes where the debug build used 48. A frame size is a property of one build. Measure the build you ship, not the one you debug.

Call, return, interrupt

The stack grows downward on screen, as it does in memory. Press Call to enter the next function, Return to leave it, and Interrupt to let a timer fire at any moment.

Illustrative frame sizes (main 16, app_loop 32, read_sensor 32, spi_xfer 24 bytes) and a 24 byte handler frame. The 32 byte exception frame is the Cortex-M one: eight words pushed by the hardware.

The part the compiler cannot see: interrupts

An interrupt is a signal that makes the CPU drop what it is doing and run a handler. It can arrive between any two instructions. So the hardware must save the interrupted code's state by itself, with no help from the program.

On Cortex-M the hardware pushes eight words on the stack that was running: r0, r1, r2, r3, r12, LR, PC and xPSR. That is 8 × 4 = 32 bytes, before the handler runs a single line. If the floating point unit was in use, the frame is bigger: the extended frame is 26 words, 104 bytes, on parts with an FPU. Press Interrupt above and watch a 32 byte block appear first, then the handler's own frame on top.

Interrupt handlers use the main stack pointer (MSP). Code under an RTOS uses a second pointer, the process stack pointer (PSP), one stack per task. The 32 byte hardware frame lands on whichever stack was running, so every task stack must have room for it. The handler's own frames land on MSP. A bare-metal program with no RTOS uses only MSP, so all of it lands on the same stack as main(). The device above shows that bare-metal case.

So the deepest the stack ever gets is the deepest call chain plus every interrupt that can nest on top of it. A measurement that forgets the interrupts is short by that much. Chapter 2 does this sum.

A Cortex-M4 (no FPU in use) takes an interrupt while main() is running. How many bytes does the hardware push before the handler's first instruction?

Chapter 2

Counting the Stack From the Code

Ask the compiler for every frame size, add them along each call path, and find the deepest one

You are packing a suitcase for a trip with three possible weather forecasts. You do not pack the average. You pack for the worst forecast, because a missing coat costs more than a spare one. The stack is the same. You must reserve room for the deepest path the program can take, not the usual path.

The first way to find that path needs no running code. It is static analysis: reading the compiled program and adding numbers on paper. It answers one question, fast: what is the largest total stack the call graph allows?

Step 1: ask the compiler for each frame

The GCC and Clang compilers have a flag, -fstack-usage. Compile with gcc -c -fstack-usage file.c and the compiler writes a .su file next to the object file. It has one line for each function: where it is, its name, the bytes of stack its frame uses, and a word for how sure the number is.

file.su# file:line:col:function   bytes   qualifier   (this lesson's example numbers)
main.c:21:5:main              16   static
app.c:40:6:app_loop           32   static
sensor.c:12:6:read_sensor     32   static
parse.c:9:6:parse             96   static
fmt.c:30:6:fmt_float         120   static
log.c:5:6:log_line            64   static
libc:vsnprintf               152   static   # often the biggest frame in a program
crc.c:3:10:crc16              24   static
isr.c:7:6:tim_isr             24   static
isr.c:19:6:uart_isr           40   static

The word static means the frame size is fixed, so the number is reliable. The word dynamic means the size depends on run-time data, as with variable-length arrays and alloca, and the number alone is unreliable. A line marked dynamic,bounded gives a reliable maximum. Review every sum that has a dynamic line in it.

There is a catch. Each line counts one frame only, not the functions it calls. The Memfault Interrupt post on this topic shows a small example: foo_2 uses 64 bytes, foo uses 80, and main uses 16. Yet the worst case for foo() is 80 + 64 = 144 bytes, because foo is still on the stack while foo_2 runs. The file alone does not show this.

Step 2: add along every path

So you need the call graph: a map of which function calls which. Draw an arrow from caller to callee. Each route from main down to a function that calls nothing is a path. The stack on a path is the sum of its frames. The worst-case stack is the largest sum over all paths.

For the example above, the paths are these. Check each sum yourself.

  1. main, app_loop, read_sensor, parse, fmt_float: 16 + 32 + 32 + 96 + 120 = 296 bytes.
  2. main, app_loop, log_line, vsnprintf: 16 + 32 + 64 + 152 = 264 bytes.
  3. main, app_loop, crc16: 16 + 32 + 24 = 72 bytes.

The worst path is the first, at 296 bytes. Notice that the big vsnprintf frame is not on the worst path. A longer chain of small frames beat it. This is why you add, instead of guessing from the biggest name.

Step 3: add the interrupts

Chapter 1 showed that an interrupt can arrive at the deepest moment. So add each interrupt that can arrive then. Each costs the 32 byte hardware frame plus the handler's own frame. If a higher-priority interrupt can preempt a lower one, add both.

With tim_isr (24 bytes) alone: 296 + 32 + 24 = 352 bytes. With uart_isr (40 bytes, higher priority) nested on top of it: 352 + 32 + 40 = 424 bytes. That is the figure to reserve, before any safety margin.

Find the worst path

Each bar is one path, built from its frames. Pick how many interrupts can pile on. Then switch on the function pointer, and compare what the tool reports with what can really happen.

Illustrative numbers, shaped like a .su file. A static tool follows direct calls only. A call through a pointer is an edge it cannot see, so its report is too low by the missing path.

Switch on the function pointer. Now parse may call vsnprintf instead of fmt_float: 16 + 32 + 32 + 96 + 152 = 328 bytes. The tool still reports 296, because the compiler cannot say what a pointer holds. The same gap appears with recursion, where the depth depends on data. These are the cases to review by hand or to measure at run time.

Tools, and where static analysis stops

Reading a .su file by eye is fine for ten functions. For a real program use a script that walks the call graph. The Interrupt post names a Python script called WorstCaseStack, the -fdump-rtl-expand compiler flag, a tool called checkStackUsage, and puncover, which draws the numbers. It notes that several need tweaks to work.

Static analysis gives a safe upper bound only if the graph is complete. It is blind to function pointers, recursion, assembly routines and library code without symbols. So treat the sum as a first number, then check it against a measurement. Chapter 3 gives you that measurement.

A .su file says foo uses 80 bytes and foo_2 uses 64 bytes. foo calls foo_2 and nothing else. What is the stack cost of calling foo()?

Chapter 3

Painting the Stack

Fill the stack with a known pattern, run the program, and read how far it really went

Smooth a tray of fine sand until it is flat. Someone walks across it with their eyes closed. When they leave, you cannot see them, but you can see the footprints. The farthest footprint shows the farthest step they took.

That is stack painting. You cannot watch every push and pop in a running chip. So you fill the stack with one known byte value before the program uses it. After a while, you look for the bytes that changed. The stack only changes what it touches.

The method, step by step

  1. Paint. Write a fill value into every byte of the stack. The Interrupt post uses 0xAA. Pick a value that is unlikely to be real data.
  2. Run. Let the program do its hardest work, so it reaches its deepest path.
  3. Scan. Start at the lowest address, the far end of the stack. Walk up while the bytes still hold the fill value. The first byte that is different is the farthest the stack ever reached.
  4. Subtract. The distance from that byte to the stack's top is the high-water mark: the most stack ever used. The distance from the bottom to that byte is the headroom, the safe space left.

Why scan from the low end? The stack grows toward lower addresses, so the deepest reach is the lowest changed byte. Bytes below it were never written.

c#define STACK_FILL 0xAA

/* Call once at startup, before the stack is in use (or only for the part below SP). */
void stack_paint(uint8_t *bottom, size_t size) {
    memset(bottom, STACK_FILL, size);
}

/* Bytes of stack ever used: size minus the untouched, still-painted run at the bottom. */
size_t stack_high_water(const uint8_t *bottom, size_t size) {
    size_t i = 0;
    while (i < size && bottom[i] == STACK_FILL) i++;
    return size - i;
}

Mind the first line of the comment. If you call memset over the live stack, you erase the frames of the code that is calling it. So paint at startup, before main() runs, or paint only the bytes below the current SP.

A worked scan

Take a 512 byte stack, painted with 0xAA. The program runs the path from Chapter 2 with one interrupt: 296 + 32 + 24 = 352 bytes. The stack top is at offset 512, so the deepest write is at offset 512 − 352 = 160. The scan walks from offset 0 and finds 0xAA in every byte until offset 160. The high-water mark is 512 − 160 = 352 bytes, and the headroom is 160 bytes. The measurement agrees with the sum.

Paint, run, scan

Each cell is 8 bytes. Pink means still painted, orange means the stack touched it. Choose a workload and press Paint, run and scan. Then switch on the partly used buffer and run it again.

Illustrative: a 512 byte stack and the Chapter 2 frame sizes. Real scans read memory with a loop like the code above. With the buffer switch on, the deepest 100 bytes of the frame are reserved but never written, so they keep the paint.

Turn on the buffer switch and run again. The scan stops 100 bytes too early. Why? The scratch buffer belongs to the deepest function. It reserved 100 bytes, but the code wrote only the high end, and the low end kept its paint. The mark says 252 bytes. The frame really reserved 352. This is the caveat the Interrupt post names: a partly used buffer hides the space it holds.

Which measurements to trust

The mark is a lower bound on the true need. It records only what this run did. A run that never took the slow error path never painted over that path's frames. So measure after the system has done all its main work, on the hardest input you have, with all interrupts active.

Real systems ship this method. FreeRTOS tracks a task's high-water mark and uxTaskGetStackHighWaterMark() returns the smallest amount of free stack the task ever had, counted in words, not bytes. A result of 0 means the task very likely overflowed. Zephyr does the same: set CONFIG_INIT_STACKS to paint, and CONFIG_THREAD_STACK_INFO too, then call k_thread_stack_space_get() for the number of unused bytes.

A third way is slow but exact. A GDB script single-steps the CPU, reads SP after every instruction, and keeps the lowest value. The Interrupt post calls it very slow and very accurate, and it needs no change to the target code. Use it to check the painted number.

Paint every stack, not only the main one. Under an RTOS each task has its own stack, and the interrupt stack on MSP is a separate one. Each stack needs its own mark. A task that sleeps most of the time can still own the deepest call path, so do not skip the quiet ones.

After you have a mark, add a margin. Many teams keep 20 to 30 percent of the stack free after the worst test. That is a rule of thumb, not a standard. Pick the number your risk allows, write it down, and check it in CI.

After a long test, a task's painted stack shows the first changed byte 90 bytes above the bottom of a 512 byte stack. What do you know?

Chapter 4

When the Stack Overflows

Watch a stack write past its end, change a variable nobody touched, and learn how to read the symptoms

Back to the greenhouse node. Its radio code builds a text line in a local array, char line[N]. Last week someone raised N from 64 to 256, to fit a longer sensor name. Everything still works on the desk. Three days later the radio is in the wrong mode and the node goes silent.

Nobody wrote to the radio mode. Yet it changed. The stack did it.

What lies below the stack

A stack is a range of RAM that the program treats as its own. The chip does not know where that range ends. It has no wall at the bottom. When SP passes the end, the push still works. It writes into whatever sits at the next lower address.

What sits there? It depends on the linker script. On a bare-metal part, the stack often starts at the top of RAM and grows down toward the heap and .bss. Under an RTOS, each task's stack is an array somewhere in RAM, and its neighbor may be another task's stack, a task control block, or a global variable. In every case, the damage lands on a thing that has nothing to do with the function that overflowed.

This is why a stack overflow is among the hardest firmware bugs to find. It is silent corruption: the write succeeds, no flag is set, and the harm appears later, somewhere else, in code that is correct.

A worked overflow, byte by byte

Take a task with a 256 byte stack. Its base cost is 160 bytes: frames and saved registers (illustrative). Directly below the stack lies a 12 byte struct of three fields, gain, offset and mode, each 4 bytes. Fields sit at rising addresses, so mode is the one nearest to the stack's end.

The task now calls a function with char line[64]. The need is 160 + 64 = 224 bytes. That fits in 256, with 32 to spare. Change N to 128: the need is 288 bytes, 32 bytes more than the stack owns. The stack pointer sits 32 bytes below the end. When the function writes its text into line, 32 bytes of that text land in memory below the stack. Text is written from low addresses upward, so the first 20 of the 32 bytes hit whatever lies beyond the struct. The last 12 cover offset, gain and mode, the fields nearest the stack.

Grow the buffer

The orange cells are the stack. The three purple cells below it are a struct the task never touches. Drag the size of line and see what the text does to the struct.

64 B

Illustrative: a 256 byte task stack, 160 bytes of other frames, and the text "TEMP=21.5C;" repeated to fill the buffer. The struct values before the overflow are gain 1, offset 0 and mode 2. The bytes are real ASCII, read as little-endian 32-bit words.

Drag past 96. The first field to break is mode, then offset, then gain. Each now holds four letters of text, read as a number. The task that reads mode later jumps to a case that does not exist. Nothing at all happened at the moment of the overflow.

Symptom, measurement, fix

Here is how it looks from the outside. A variable has a value no line of code could give it. A task crashes in a function that has no bug. A HardFault points to a random place, and it moves when you add a printf. The fault goes away under the debugger, because debug builds often lay out RAM differently. Several of these together point at memory corruption, and a stack is the first suspect.

The measurement is Chapter 3. Paint the stack and run the failing scenario. If the scan finds the whole stack changed, down to the last byte, the stack reached its floor. A high-water mark that touches the bottom is the sign of an overflow. FreeRTOS reports it as a high-water mark of 0 words. Then use Chapter 2 to find which path is the deep one.

FreeRTOS can also check for you. Its configCHECK_FOR_STACK_OVERFLOW option looks at a task's stack when the task is switched out. That helps, but it is late: it runs after the stack has already overrun, so it flags the damage and does not prevent it.

The fix comes in three forms, in this order of preference:

  1. Remove the cause. Move the large buffer out of the stack. A static buffer sits in .bss, where the linker counts it. Replace deep recursion with a loop. Cut nesting. Shorten printf-style calls, which carry large frames.
  2. Make the stack larger, based on the measured mark plus a margin, not on a guess.
  3. Make the failure loud. A write that faults at the exact line is far easier to fix than a corrupted variable days later. Chapters 7 and 8 build that.

Now make line a static array. The device would show a stack cost of only the 160 byte base, and the corruption is gone. The buffer's bytes now show up in .bss, in the link map, where a review can see them. That is the general trade: static memory is fixed, visible and checked by the linker.

A configuration variable changes by itself. No code writes it. A painted-stack scan shows the stack's last byte was overwritten. What is the most likely cause?

Chapter 5

The Heap and Its Fragments

Free some blocks, keep others, and watch a request fail even though plenty of memory is free

A car park has 32 bays in one row. Short cars take one bay, vans take two, a bus takes four. Cars arrive and leave all day, in no fixed order. By the evening, half the bays are empty. A bus drives in and cannot park, because the empty bays are scattered in ones and twos between parked cars. There is room in total. There is no room in one piece.

That is the whole story of heap fragmentation. The rest of this chapter shows it happening to malloc.

What malloc does

The heap is a region of RAM that a part of your program, the allocator, hands out in pieces. You call malloc(n), and the allocator finds a free piece of at least n bytes and returns its address. You call free(p) to give the piece back. The allocator keeps a list of the free pieces, the free list.

A common rule is first fit: take the first free piece on the list that is big enough, and split it if it is too large. Another is best fit: take the smallest piece that is big enough. When you free a piece, a good allocator coalesces it: it merges it with free neighbours into one larger piece. Without that step, free memory only ever splits into smaller bits.

Real allocators also store a small header in front of each piece, with its size, so free knows how much to give back. This lesson's model leaves headers out to keep the numbers readable.

The failure, with numbers

Use a heap of 512 bytes, with a 16 byte step: 32 cells. The task allocates five blocks in a row and keeps the order:

  1. A: 64 bytes at cells 0 to 3. B: 128 bytes at cells 4 to 11.
  2. C: 64 bytes at cells 12 to 15. D: 128 bytes at cells 16 to 23.
  3. E: 64 bytes at cells 24 to 27. The last 64 bytes (cells 28 to 31) are still free.

Now free A, C and E. The free list holds A (64), C (64), and E joined to the tail: 64 + 64 = 128. Total free memory is 64 + 64 + 128 = 256 bytes, half of the heap. The largest single piece is 128 bytes. Ask for malloc(192). The allocator finds no piece of 192 and returns NULL, with 256 bytes free.

Fragment a heap

Press Load the story for the five blocks above. Tap a block to free it. Then press malloc 192. You can also allocate your own blocks and free them in any order.

A model: 512 bytes, 16 byte cells, first fit, free blocks merged with free neighbours, no headers. Real allocators add a header to each block and round sizes up. The story is this chapter's own worked example.

Load the story, free A, C and E, and press malloc 192. Then free D as well. D (128 bytes) sits between the free C and the free E, so everything from C onward becomes one run: C, D and E and the tail. The largest piece jumps from 128 to 320 bytes, and the same request now works. Coalescing is what turns free bits back into one useful block.

Why firmware suffers more than a laptop

A laptop has a memory management unit and virtual memory. It can remap pages and swap. A small microcontroller has none of this. Free bytes are free bytes at fixed addresses, and a hole stays a hole.

The program also runs for months. A fragmentation pattern that takes a week of odd message sizes to build is invisible in a ten minute test. The failure then appears as a NULL that no one checked, on a Sunday, in the field.

The time cost matters too. malloc walks a list. Its run time depends on how fragmented the heap is, so it is not bounded. Code that must meet a deadline (see real-time systems) should not call it.

Measure it, then choose

Track two numbers, not one: the total free bytes and the largest free block. If the first is large and the second is small, the heap is fragmented. Also track the minimum free ever seen. FreeRTOS exposes the free total with xPortGetFreeHeapSize() and the all-time minimum with xPortGetMinimumEverFreeHeapSize().

FreeRTOS also ships several allocators, and the choice matters. In its documentation, heap_2 uses best fit, lets blocks be freed, and does not merge neighbours, so it fragments with mixed sizes. heap_4 merges adjacent free blocks to limit fragmentation. heap_3 wraps the C library's malloc. heap_5 uses heap_4's method over several separate RAM regions. heap_1 never frees at all, which cannot fragment but cannot recycle either.

The deepest fix is to stop allocating and freeing on the hot path. Some coding standards for safety code, MISRA C among them, forbid the C library allocator for this reason. The next chapter shows what to use instead.

A heap has 256 bytes free in total, and malloc(192) returns NULL. What explains it?

Chapter 6

Pools and Static Allocation

Give every message a bay of the same size, and the heap's worst failure cannot happen

Go back to the car park. Suppose you repaint it so that every bay is the same size, big enough for the largest vehicle. A small car wastes some of its bay. But now any empty bay fits any vehicle. A bus can never be turned away while a bay is free.

That trade is the idea of a memory pool: a set of equal-sized blocks, handed out and taken back one at a time. You give up a little space inside each block. You gain a guarantee that the heap cannot give.

Three steps away from malloc

Firmware has a ladder of choices, from the most flexible to the most predictable.

  1. The general heap. Any size, any order, fragmentation possible. This is Chapter 5.
  2. Allocate once, never free. Take memory from the heap at start-up for things that live as long as the program. A heap that never frees cannot fragment. FreeRTOS's heap_1 works this way.
  3. Static allocation. Declare each object as a global or static variable. The linker places it, and the link map lists its size. No call can fail at run time. Zephyr and FreeRTOS both offer calls that take a buffer you supply instead of one they allocate, such as FreeRTOS's xTaskCreateStatic().

A pool sits between the second and third step. It is static memory, split into equal blocks, with an allocator so small it fits on one page.

How a pool works

Declare an array of N blocks, each B bytes. Chain the free blocks into a list. A free list is a list that uses the free blocks themselves for its links: the first bytes of each free block hold a pointer to the next free block. No extra memory is needed.

To allocate, remove the first block from the list and return it. To free, push the block back at the front. Both are a few instructions, so the time is constant: it does not depend on how many blocks are free or in what order. That is the property a deadline needs.

c#include <stdint.h>
#include "cmsis_compiler.h"                       /* __get_PRIMASK, __disable_irq, __set_PRIMASK */

#define BLOCK_SIZE   80                       /* the largest message: 5 x 16 bytes, multiple of 8 */
#define BLOCK_COUNT  6                        /* the design limit on live messages */

typedef struct block { struct block *next; } block_t;

static uint8_t pool_mem[BLOCK_COUNT][BLOCK_SIZE] __attribute__((aligned(8)));  /* in .bss: the linker counts it */
static block_t *free_head;

void pool_init(void) {
    free_head = NULL;
    for (int i = BLOCK_COUNT - 1; i >= 0; i--) {
        block_t *b = (block_t *)pool_mem[i];
        b->next = free_head;                     /* chain every block into the free list */
        free_head = b;
    }
}

void *pool_alloc(void) {
    uint32_t pm = __get_PRIMASK(); __disable_irq();   /* an interrupt may also call this */
    block_t *b = free_head;
    if (b) free_head = b->next;                 /* O(1): take the first block */
    __set_PRIMASK(pm);
    return b;                                  /* NULL only when all BLOCK_COUNT are in use */
}

void pool_free(void *p) {
    block_t *b = p;
    uint32_t pm = __get_PRIMASK(); __disable_irq();
    b->next = free_head;                         /* O(1): push it back */
    free_head = b;
    __set_PRIMASK(pm);
}

The disable and restore of interrupts keeps a handler from changing the list half way through an update. Without them, two callers could take the same block. The critical section is a few instructions long.

Same RAM, same workload

Now race them. Give both 480 bytes. The heap is 30 cells of 16 bytes. The pool is 6 blocks of 80 bytes. The program handles messages of 32 to 80 bytes, and never more than 6 are alive at once. That limit is a design decision, enforced by the queue depth. Replay the same random sequence of arrivals and departures on both.

Heap or pool, same 480 bytes

Drag the number of events, or press Play. Blue blocks are live messages. The top strip is the heap. The bottom strip is the pool: six fixed bays. Red marks a request that failed.

70

A model with a seeded random sequence (the same on every visit for a given sequence number). Messages are 2 to 5 cells of 16 bytes (32 to 80 bytes). The heap uses first fit and merges free neighbours, with no headers. The pool block is 5 cells, so small messages waste the rest of their bay.

Try a few sequences. The heap fails at the moments its free cells are split. The pool never fails, because six bays always hold six messages. Look at the cost too: a 32 byte message holds a whole 80 byte bay. That wasted space, inside a block, is internal fragmentation. The heap's scattered holes are external fragmentation. A pool trades the second for the first, and the first is the one you can compute in advance.

Sizing a pool, and when it runs out

Choose B as the largest object. If sizes vary a lot, use several pools, one for each size class: 32, 80 and 256 bytes, for example. Choose N as the largest number of live objects, found from the design (a queue depth) and from a measured peak. Then add a margin.

A pool can still run out. The difference is how. pool_alloc returns NULL exactly when N blocks are live, which is a clear, testable condition you can count and log. A heap fails at a moment that depends on history. Zephyr offers the same idea as memory slabs (k_mem_slab), and RTOSes expose pools as part of their message queues.

Pools suit message buffers, packets, events and small records. Take care with one bug: a double free. If code frees the same block twice, the free list holds that block twice, and two later callers receive the same bytes. A debug build can keep a count of live blocks, or mark each free block, and stop at the second free.

Why does a fixed-size block pool avoid the failure from Chapter 5, where 256 bytes were free but malloc(192) failed?

Chapter 7

The Memory Protection Unit

Build a region from a base, a size and a permission, and see why alignment decides what it covers

Think of an office building where every door has a lock, and each lock holds a short list of rules. "Addresses 100 to 199: staff may read and write, visitors may not enter." A guard checks the list on every single access, before the door opens. The guard is fast, because the list is short: eight rules.

The memory protection unit, or MPU, is that guard. It is a small block inside the CPU that checks every memory access against up to eight rules, in hardware, with no extra cycles. It is optional, so check that your part has one. The Cortex-M0+, M3 and M4 have 8 regions, and the Cortex-M7 up to 16. The DREGION field of MPU_TYPE tells you how many yours has, and 0 means there is no MPU.

One region, four questions

A region is one rule. It answers four questions about a range of addresses.

  1. Where? A base address, and a size. The size must be a power of two: 2SIZE+1 bytes, where SIZE is a 5-bit field. SIZE = 5 gives 64 bytes. SIZE = 16 gives 128 KB.
  2. Aligned how? The base address must be a multiple of the size. A 64 byte region can start at 0x...40 or 0x...80, but not at 0x...A0.
  3. Who may do what? The access permission field, AP, says whether privileged code (the kernel, handlers) and unprivileged code (tasks) may read or write.
  4. May code run here? The XN bit ("execute never") blocks instruction fetches from the region.

The minimum region size depends on the chip. It is usually 32 bytes. The Interrupt post shows how to read it: write 0xFFFFFFE0 to MPU_RBAR, read it back, and count the zero bits at the low end. A readback of 0xFFFFFF80 means 128 bytes.

The power-of-two rule is the part that surprises people. You cannot say "protect 100 bytes starting here". You pick 64 or 128, aligned, or you use several regions. Larger regions can also be split into eight equal subregions, each switched on or off by a bit of the SRD field. This works only for bigger regions, from about 256 bytes upward. Check your core's manual for the exact edge.

The registers

RegisterAddressWhat it does
MPU_TYPE0xE000ED90Reports how many regions exist (DREGION)
MPU_CTRL0xE000ED94ENABLE the MPU, PRIVDEFENA for a default background map
MPU_RNR0xE000ED98Selects which region the next two writes configure
MPU_RBAR0xE000ED9CBase address, with VALID and the region number in the low bits
MPU_RASR0xE000EDA0Size, access permission, XN, memory attributes, enable

Writing base | (1 << 4) | n to MPU_RBAR sets the base and selects region n in one write. The VALID bit is bit 4. In MPU_RASR, ENABLE is bit 0, SIZE is bits 5:1, SRD is bits 15:8, the memory attributes (TEX, S, C, B) are bits 21:16, AP is bits 26:24 and XN is bit 28.

When regions overlap, the one with the highest number wins. In MPU_CTRL, set PRIVDEFENA to let privileged code use the chip's normal memory map wherever no region applies. That map has the lowest priority, so any configured region overrides it. With the bit clear, any access no region allows will fault.

A worked region: guard the bottom of a stack

The Interrupt post guards 64 bytes at the bottom of the stack on an nRF52840, with the linker symbol __StackLimit at 0x2003E000. Build the registers by hand. Region 0, no access (AP = 0b000), attributes TEXSCB = 0b000110, 64 bytes means SIZE = 5 because 26 = 64.

MPU_RBAR = 0x2003E000 | 0x10 | 0 = 0x2003E010. MPU_RASR = (0 << 24) | (6 << 16) | (5 << 1) | 1 = 0x60000 + 0xA + 1 = 0x0006000B. Then MPU_CTRL = 0x5 turns on ENABLE and PRIVDEFENA.

Build a region

Teal outlines the 64 bytes you want to guard. The pink band is what the hardware covers. Choose a target, then change SIZE. Try the third target.

5 = 64 B

The register layout is the Cortex-M3/M4 one in the Interrupt post. TEXSCB is fixed at 0b000110 as in its stack guard example. The values are computed live from the fields. The hardware masks the low bits of an unaligned base, which is what the pink band shows.

Pick the third target, 0x2003E0A0, with SIZE = 5. The base is not a multiple of 64, so the hardware drops the low bits and the region lands at 0x2003E080. It covers 0xE080 to 0xE0BF. Your target ran from 0xE0A0 to 0xE0DF. Half is covered and half is not, and 32 bytes of the wrong place are covered instead. Raise SIZE to 6 (128 bytes) and the aligned base becomes 0xE080, which covers the target, at the price of guarding 64 extra bytes.

Turn it on safely

Faults from the MPU raise the MemManage fault on Cortex-M3, M4 and M7. (The Cortex-M0+ has no MemManage fault, so there a violation is always a HardFault.) It is off by default. Until you set MEMFAULTENA (bit 16 of SHCSR at 0xE000ED24), an MPU violation escalates to a HardFault. Chapter 8 shows both.

You write an MPU region with SIZE = 5 and a base of 0x2003E0A0. What does the hardware protect?

Chapter 8

A Guard That Faults

Put a locked strip below the stack, run too deep, and read the fault that names the line

A hiker walks along a cliff path in fog. A low fence runs along the edge. She cannot see the drop, but she knows the moment she touches the fence. Without it, she would find out one step later.

A stack guard is that fence. It is a small region of memory, just below the stack, that nobody may touch. Chapter 7 built one: 64 bytes, no access. If the stack grows into it, the MPU stops the write on the spot.

What happens when the stack touches the guard

The store that reaches the guard does not complete. The CPU raises a MemManage fault, an exception that the MPU uses. The processor saves eight words on the stack, as in Chapter 1, and runs MemManage_Handler. Two settings must be right first. MEMFAULTENA in SHCSR must be 1. If it is 0, the fault escalates to a HardFault. And the MPU must be enabled, as in Chapter 7.

The handler can read what went wrong from two registers. MMFSR is the MemManage status byte at 0xE000ED28. MMFAR at 0xE000ED34 holds the faulting address, but only when the bit MMARVALID in MMFSR is set. The stacked PC, word 6 of the saved frame, is the address of the instruction that did the store.

  1. Bit 0, IACCVIOL: an instruction fetch was not allowed.
  2. Bit 1, DACCVIOL: a data load or store was not allowed.
  3. Bit 4, MSTKERR: pushing the exception frame itself caused a violation.
  4. Bit 7, MMARVALID: MMFAR holds the faulting address.

In the Interrupt post's test, a recursion to depth 600 produced MMFSR = 0x92 and a fault address of 0x2003E038, just above the guard's base. Decode 0x92 = 1001 0010: bit 7 (MMARVALID), bit 4 (MSTKERR) and bit 1 (DACCVIOL). The data store hit the guard, and the hardware then failed to push the exception frame, because the stack pointer was already inside the guard. A plain store with room left gives 0x82. The address 0x2003E038 lies in the 64 byte guard from 0x2003E000.

c/* The fault entry: pick the stack that was running, then hand its frame to C. */
__attribute__((naked)) void MemManage_Handler(void) {
    __asm volatile(
        "tst lr, #4      \n"   /* EXC_RETURN bit 2: 1 = PSP was in use, 0 = MSP */
        "ite eq         \n"
        "mrseq r0, msp  \n"
        "mrsne r0, psp  \n"
        "b mem_fault_c  \n");
}

void mem_fault_c(uint32_t *frame) {          /* frame: r0 r1 r2 r3 r12 lr pc xpsr */
    uint8_t  mmfsr = *(volatile uint8_t  *)0xE000ED28;
    uint32_t mmfar = *(volatile uint32_t *)0xE000ED34;
    uint32_t pc    = frame[6];                   /* the store that hit the guard */
    log_fault(mmfsr, (mmfsr & 0x80) ? mmfar : 0, pc);   /* save to RAM that survives, then reset */
    for (;;) { }
}

The next step is to look up pc in the map file (the toolchain lesson) or with addr2line. It names the exact function. That is the payoff: instead of a variable that changed for no reason, you get a stack trace at the moment of the overflow. The debugging lesson goes further with fault decoding.

See it, and see where it fails

Hit the guard

Choose the protection and the call depth. Then switch on the large array in the deepest function, which moves SP a long way in one step. See which protection catches it early.

8

A model with the hero's illustrative numbers: 2,048 byte stack at 0x20003800, 64 byte guard, base frame 64 bytes plus 192 per call. The array is filled from index 0 upward, as a memset or a loop does. The stack limit mode models the Armv8-M PSPLIM and MSPLIM registers.

Leave the MPU guard on, set depth 8, and switch on the array. The frame needs 1,600 + 512 = 2,112 bytes, so SP lands 64 bytes below the stack's end, under the guard. The loop that fills the array writes upward from index 0. The first 64 bytes land in the heap with no fault. Only when the loop reaches the guard does the MPU stop it, and the damage below is done. A guard catches a step onto it. It cannot catch a jump over it.

There are two fixes. Make the guard larger than your largest frame, or warn at build time: GCC's -Wframe-larger-than=N and -Wstack-usage=N flag any function whose frame passes N bytes. The Chapter 2 sum then has a hard rule behind it.

Stack limit registers on Armv8-M

Newer cores add the check to the stack pointer itself. Armv8-M, found in the Cortex-M33, adds two registers, MSPLIM and PSPLIM. You set each to the bottom of its stack. When SP would go below the limit, the core raises a UsageFault and sets the sticky bit STKOF (bit 4 of UFSR). Because the check is on SP, a big array is caught when SP moves, before any byte is written. The architecture also defines what happens when exception stacking would cross the limit, so a handler does not corrupt memory.

Switch the device to Stack limit with the array on. It faults at the instruction that moves SP, and the heap is untouched. The cost is that older cores (Cortex-M0+, M3, M4 and M7) do not have these registers, so there the MPU guard is the tool.

Real systems use both ideas. An RTOS can place a write-protected guard before each task's stack, and Zephyr's thread documentation describes this guard-based detection. FreeRTOS has MPU ports that give each task its own regions. Pair the guard with the painted-stack measurement of Chapter 3: the guard stops damage, the paint tells you how much margin is left before it triggers.

With a 64 byte MPU guard below the stack, a function declares a 512 byte local array and fills it from index 0. SP lands 64 bytes below the guard. What happens?

Chapter 9

The Field Guide

Keep the numbers, the checklist and the core code for the next time a chip resets with no message

The greenhouse node had a stack that grew past its end. Now you know the whole path. A chip has one RAM, shared by static data, a heap and stacks. You measure the stack with the compiler and with paint. You remove heap fragmentation with pools. You make a wrong write loud with a guard.

Check your stack margin

How much margin is left?

Set the stack size you ship and the high-water mark from a painted-stack run. The bar shows the used part, the headroom and the margin you chose.

1,024 B
672 B
25%

A calculator. The margin percentage is a rule of thumb, not a standard: this lesson uses 25%. The suggested size is the mark divided by (1 minus the margin), rounded up to a multiple of 8 bytes, the stack alignment.

The numbers that matter

WhatNumberWhy it matters
Exception frame, Cortex-M8 words = 32 bytes (r0 to r3, r12, LR, PC, xPSR)Every interrupt adds this before its handler runs
Extended frame, FPU in use26 words = 104 bytesSize task stacks for it on parts with an FPU
Static worst case, example296 B path + 56 B (one interrupt) = 352; + 72 B nested = 424Sum frames along the worst path, then add interrupts
Interrupt post examplefoo 80 + foo_2 64 = 144 bytesA .su line counts one frame, not its callees
Stack paint value0xAA in the Interrupt postScan from the far end for the first changed byte
FreeRTOS high-water markminimum free stack ever, in words; 0 means likely overflowWords, not bytes, on stock FreeRTOS
Heap, worked example256 B free in total, largest piece 128 B, malloc(192) failsTrack the total and the largest piece
MPU regions8 on Cortex-M0+, M3, M4; up to 16 on M7Plan which memory deserves a region
Region size2^(SIZE+1) bytes; base a multiple of the sizeSIZE 5 = 64 B; SIZE 16 = 128 KB
Stack guard, nRF52840 exampleRBAR 0x2003E010, RASR 0x0006000B, CTRL 0x564 bytes, no access, at __StackLimit
MemManage faultMMFSR at 0xE000ED28, MMFAR at 0xE000ED34, SHCSR bit 16Read the address and the stacked PC
Armv8-M stack limitMSPLIM, PSPLIM; UFSR bit 4 is STKOFCatches a big frame before any byte is written

The checklist

  1. Know the budget. Write down static, heap and stack bytes for your RAM, with the peak you measured for each.
  2. Sum the worst path. Use -fstack-usage, add along the call graph, add every interrupt, and review every dynamic and function pointer edge.
  3. Paint and run. Measure the high-water mark under the hardest test. Keep your margin after the worst run.
  4. Move big buffers out of the stack, or warn on large frames with -Wstack-usage.
  5. Do not free on the hot path. Allocate at start-up, or use pools. Count the failures of any allocator you keep.
  6. Add a guard. Use an MPU region below each stack, or the stack limit registers on Armv8-M. Enable MemManage and decode the fault.
  7. Put the checks in CI. Fail the build if the stack sum or the mark crosses your limit.

The core as code

c/* 1. Paint and read the high-water mark (Chapter 3) */
void   stack_paint(uint8_t *bottom, size_t size)  { memset(bottom, 0xAA, size); }
size_t stack_high_water(const uint8_t *bottom, size_t size) {
    size_t i = 0; while (i < size && bottom[i] == 0xAA) i++;
    return size - i;                                  /* bytes ever used */
}

/* 2. A pool: O(1), no fragmentation (Chapter 6): pool_init / pool_alloc / pool_free above */

/* 3. An MPU stack guard on a Cortex-M3/M4 (Chapters 7 and 8) */
#define MPU_CTRL (*(volatile uint32_t *)0xE000ED94)
#define MPU_RBAR (*(volatile uint32_t *)0xE000ED9C)
#define MPU_RASR (*(volatile uint32_t *)0xE000EDA0)
#define SHCSR    (*(volatile uint32_t *)0xE000ED24)
extern uint8_t __StackLimit[];                       /* linker symbol, aligned to 64 bytes */

void mpu_guard_stack(void) {
    MPU_RBAR = (uint32_t)__StackLimit | (1u << 4) | 0;      /* base, VALID, region 0 */
    MPU_RASR = (0u << 24) | (0x06u << 16) | (5u << 1) | 1u;   /* AP no access, TEXSCB 000110, 64 B, enable */
    MPU_CTRL = 0x5;                                    /* ENABLE | PRIVDEFENA */
    SHCSR   |= (1u << 16);                         /* MEMFAULTENA */
    __DSB(); __ISB();                                   /* make the new rules take effect now */
}

Where this sits

This lesson stays below the operating system. The RTOS survey and RTOS internals give each task its own stack, which is where per-task painting and per-task guards pay off. The privilege lesson explains the privileged and unprivileged levels that the AP field refers to.

Next in this series, debug and trace turns the fault registers of Chapter 8 into a full post-mortem, flash storage covers the other memory, and drivers and state machines shows how to design code that needs less of everything. A neural network on a small chip makes the same budget tight in a new way: the tensor arena is a static pool.

Keep going

Sources and credit

The takeaway. RAM has no walls unless you build them. Measure the stack twice, once from the code and once with paint. Replace the churn of malloc with blocks of fixed size. Then add a guard, so the next overflow stops at the exact line instead of showing up as a mystery three days later.
Which set of steps follows this lesson for a new firmware project?

Now press Present or Teach and explain, from memory, why the greenhouse node reset every three days and what you would measure first. Then go back to the instrument at the top and run the stack into its guard once more.

Where Memory Goes: Firmware from Zero, lesson 6
Measuring stack usage · The MPU on Cortex-M · Back to the firmware on-ramp