---
title: Memory on small machines
heading: Flash, RAM, the stack and why embedded code avoids the heap
eyebrow: C12 · Lesson 5 · Memory on small machines
xp: 40
---

::: hook
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.
:::

::: play
- 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.
:::

```sim plot
view: graph
x: d = 0..200
y: B = 0..40000 bytes
slider: D = 1000..20000 step 500 = 8000 bytes
slider: F = 16..512 step 16 = 96 bytes
slider: R = 8192..32768 step 4096 = 16384 bytes
plot: D + F*d | label: data plus stack
plot: R + 0*d | dashed | label: RAM
readout: deepest call chain that fits = (R - D)/F | digits: 4
```

::: 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?

- [ ] 512 bytes
- [x] About 10 KB
- [ ] Nothing: local arrays live in flash
- [ ] 20 bytes

::: reveal
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.
:::
:::

::: nameit
## 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.
:::

::: 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?

::: solution
1. **Add up what's used.**
   $$2 + 5 + 3 = 10\ \text{KB}$$
   which leaves 6 KB free.
2. **Add the buffer as a global.** It goes in .bss, which leaves 2 KB.
3. **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.
:::
:::

::: 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?

::: solution
1. **The call chain.**
   $$12 \times 48 = 576\ \text{bytes}$$
2. **The interrupts on top.**
   $$2 \times 64 = 128\ \text{bytes}$$
3. **Add them.**
   $$576 + 128 = 704\ \text{bytes}$$
4. **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%.
:::
:::

::: 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?

::: solution
1. **Subtract the untouched part.**
   $$2048 - 1350 = 698\ \text{bytes}$$
   were used at the deepest point.
2. **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
kind: parts
given: R = 8 | 16 | 32; a = 1 | 2; b = 3 | 6; s = 1 | 2 | 4

## A chip has {R} KB of RAM; the program has {a} KB of .data, {b} KB of .bss and a {s} KB stack.

::: part
answer: R - a - b - s
unit: KB
tolerance: 0.5%

### How much RAM is free?

::: misses
- [R - b - s] .data lives in RAM too, after it's copied from flash.
- [any] RAM less data, bss and stack.
:::
:::

::: part
answer: (a + b + s)/R*100
unit: %
tolerance: 0.5%

### What share is used?

::: misses
- [any] Used over total.
:::
:::
:::

::: check
kind: parts
given: n = 8 | 15 | 30; f = 32 | 48 | 96; k = 1 | 2; g = 48 | 64

## The deepest call chain is {n} frames of {f} bytes, and {k} interrupt level(s) of {g}-byte frames can stack on top.

::: part
answer: n*f + k*g
unit: bytes
tolerance: 0

### How much stack does it need?

::: misses
- [n*f] Add the interrupt frames that can land on top.
- [any] Calls plus interrupts.
:::
:::

::: part
answer: 1.3*(n*f + k*g)
unit: bytes
tolerance: 0.5%

### What should be reserved with a 30% margin?

::: misses
- [any] 1.3 times that.
:::
:::
:::

::: check
kind: parts
given: S = 1024 | 2048 | 4096; u = 300 | 900 | 1500

## A painted stack of {S} bytes still has its lowest {u} bytes untouched after testing.

::: part
answer: S - u
unit: bytes
tolerance: 0

### What is the high-water mark?

::: misses
- [u] Those bytes were never used.
- [any] Stack size less the untouched part.
:::
:::

::: part
answer: u/S*100
unit: %
tolerance: 0.5%

### What share of the stack was never used?

::: misses
- [any] Untouched over total.
:::
:::
:::

::: check
kind: parts
given: n = 64 | 256 | 1024; w = 1 | 2 | 4

## A lookup table has {n} entries of {w} bytes.

::: part
answer: n*w
unit: bytes
tolerance: 0

### How much flash does it take if it's declared `const`?

::: misses
- [any] Entries × size.
:::
:::

::: part
answer: n*w
unit: bytes
tolerance: 0

### How much RAM does it waste if `const` is forgotten?

::: misses
- [0] Without `const` it's .data: copied into RAM at startup.
- [any] The whole table.
:::
:::
:::

::: check
kind: choice

## Why do long-running embedded programs avoid `malloc` and `free`?

- [ ] They're too slow on small processors
- [x] Repeated allocation and freeing fragment the heap, so a request can eventually fail even with enough total memory free
- [ ] The heap lives in flash
- [ ] C on microcontrollers doesn't have them

::: misses
- [1] Speed is a smaller concern than eventual failure.
- [3] The heap is in RAM.
- [4] Most toolchains provide them; the point is not to rely on them.
:::
:::

::: check
kind: python

## 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 starter
def high_water(stack, pattern):
    return 0
```

```python solution
def high_water(stack, pattern):
    untouched = 0
    for b in stack:
        if b != pattern:
            break
        untouched += 1
    return len(stack) - untouched
```

```python tests
assert high_water([0xAA] * 1350 + [0x12] * 698, 0xAA) == 698, "1350 untouched of 2048: 698 used."
assert high_water([0xAA] * 100 + [0x00, 0xAA, 0x55] + [0xAA] * 20, 0xAA) == 23, "A pattern byte that happens to be written above the mark still counts as used."
assert high_water([0xAA] * 64, 0xAA) == 0, "Never touched: 0."
assert high_water([0x01] + [0xAA] * 63, 0xAA) == 64, "Touched at the very bottom: all of it."
```

::: right
Right. Scanning from the bottom up finds the deepest write, even if some bytes above it happen to hold the pattern.
:::
:::

::: explain
## Why does a stack overflow on a microcontroller often cause a failure far from where it happened?

::: model
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
::: check
given: R = 12 | 64; u = 7 | 40
answer: R - u
unit: KB
tolerance: 0.5%

## {u} KB of a {R} KB RAM is used. How much is free?

::: misses
- [any] Total less used.
:::
:::

::: check
given: n = 10 | 25; f = 40 | 80
answer: n*f
unit: bytes
tolerance: 0

## Stack for {n} frames of {f} bytes?

::: misses
- [any] Frames × size.
:::
:::

::: check
given: S = 2048 | 8192; u = 512 | 3000
answer: S - u
unit: bytes
tolerance: 0

## High-water mark of a {S}-byte stack with {u} bytes untouched?

::: misses
- [any] Size less untouched.
:::
:::
:::
