C12 · Lesson 5 · Memory on small machines
Flash, RAM, the stack and why embedded code avoids the heap
A desktop program can assume gigabytes of memory and an operating system that reports when it runs out. A microcontroller has a few kilobytes of RAM, no warning, and nothing between the stack and the variables below it. When the stack grows too deep it silently overwrites data, and the program fails somewhere unrelated, hours later. Embedded programmers therefore budget memory the way they budget time: every buffer, every table and every level of call depth is counted before it ships.
- The rising line is the RAM a program needs as its deepest chain of calls gets longer: its fixed data (.data and .bss) plus one stack frame per level.
- The flat line is the chip's RAM. Where they cross, the stack runs into the variables.
- Shrink the frames (fewer local variables, no large arrays on the stack) and the same RAM allows much deeper calls.
Predict
A function declares uint8_t buf[512]; as a local variable and calls itself recursively 20 levels deep. How much stack do those buffers take?
About 10 KB: every level gets its own 512-byte buffer on the stack, 20 × 512 = 10,240 bytes, more than many small chips have in total. Declaring the buffer static puts one copy in .bss instead, and avoiding recursion makes the depth knowable.
Name it
Where things live
| Section | Holds | Lives in |
|---|---|---|
| .text | code | flash |
| .rodata | const tables and strings | flash |
| .data | initialized globals | RAM, with initial values copied from flash at reset |
| .bss | zeroed globals | RAM |
| stack | locals, return addresses, saved registers | RAM, growing down |
| heap | malloc | RAM, growing up, if used at all |
A const table stays in flash and costs no RAM; the same table without const is copied into RAM at startup.
The stack
Each call pushes a frame: the return address, saved registers and the function's locals. The deepest path through the call graph, plus the frames of any interrupts that can land on top of it, sets the stack the program needs. Recursion makes that depth depend on the data; embedded code avoids it, or bounds it.
Measuring it
Stack painting: at startup, fill the stack region with a known pattern such as 0xAA. After running the worst cases, scan for the deepest byte that changed. That high-water mark is the measured stack use; leave a margin above it.
Why no heap
malloc and free fragment memory over time: after enough allocations of different sizes, a request can fail although enough total memory is free. On a device that must run for years, that failure is just a matter of time, so embedded code allocates everything statically, or from fixed-size pools, at startup.
Worked example
A chip has 16 KB of RAM. The program has 2 KB of .data, 5 KB of .bss and reserves 3 KB for the stack. How much is left, and what if a 4 KB frame buffer is added as a global?
Show the solution
- Add up what's used. which leaves 6 KB free.
- Add the buffer as a global. It goes in .bss, which leaves 2 KB.
- Declare it in a function instead. That would put it on the stack, overflowing the 3 KB reserved there, which is the kind of bug that appears only when that function runs.
Answer 6 KB is left, and 2 KB once the 4 KB buffer is added as a global.
Worked example
The deepest call chain is 12 functions with frames averaging 48 bytes, and two nested interrupt levels can land on top of it with 64-byte frames. How much stack is needed?
Show the solution
- The call chain.
- The interrupts on top.
- Add them.
- Choose the reserve. A 30% margin calls for 1.3 × 704 = 915 bytes, so reserve 1 KB. That leaves 320 spare bytes, a margin of about 45% over the estimate, which a stack-painting test should confirm on the real worst case.
Answer 704 bytes; reserving 1 KB leaves a margin of about 45%.
Worked example
A 2 KB stack was painted with 0xAA at reset. After a long test, the lowest 1350 bytes still hold 0xAA. What is the high-water mark?
Show the solution
- Subtract the untouched part. were used at the deepest point.
- Resize the stack. With 1350 bytes never touched, the stack could be cut to 1 KB and still keep a margin of about 47% (1024/698 = 1.47), freeing 1 KB of RAM.
Answer the high-water mark is 698 bytes.
Check
A chip has 16 KB of RAM; the program has 1 KB of .data, 6 KB of .bss and a 4 KB stack.
(a)
How much RAM is free?
(b)
What share is used?
Check
The deepest call chain is 15 frames of 32 bytes, and 2 interrupt level(s) of 64-byte frames can stack on top.
(a)
How much stack does it need?
(b)
What should be reserved with a 30% margin?
Check
A painted stack of 2048 bytes still has its lowest 300 bytes untouched after testing.
(a)
What is the high-water mark?
(b)
What share of the stack was never used?
Check
A lookup table has 256 entries of 1 bytes.
(a)
How much flash does it take if it's declared const?
(b)
How much RAM does it waste if const is forgotten?
Check
Why do long-running embedded programs avoid malloc and free?
Check
Write high_water(stack, pattern): stack is a list of byte values from the lowest address to the highest, painted with pattern at reset (the stack grows down from the top). Return how many bytes were used: the stack's length less the run of untouched bytes at the bottom.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Explain why
Why does a stack overflow on a microcontroller often cause a failure far from where it happened?
On most small microcontrollers there's no memory protection between the stack and the variables next to it. When the stack grows past its reserved area, it simply writes over whatever globals sit below, without any error. The function that overflowed carries on normally and returns; the damage shows up later, when some other code reads the corrupted variable and behaves strangely, crashes, or the watchdog resets the device. The symptom is unrelated to its cause in both place and time, which is why stacks are budgeted in advance and checked with painting rather than discovered in the field.
Practice
Keep practicing
7 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.