---
title: Dynamic memory and linked structures
heading: The heap, what malloc costs, and following pointers through memory
eyebrow: C8 · Lesson 12 · Dynamic memory and linked structures
xp: 40
---

::: hook
Arrays and structs (lessons 10 and 11) have sizes fixed when the program is written. Real programs build lists of network packets, trees of file names and queues of events whose sizes aren't known until they run. That memory comes from the **heap**, handed out by `malloc` and returned by `free`, and it's linked together by pointers: each item holds the address of the next. To the processor a linked list is just loads, each one's address coming from the previous load. That makes it flexible, and slow, and it gives the heap its own failure modes: leaks, fragmentation, and overhead that can exceed the data itself.
:::

::: play
- Three list nodes sit in memory, each a value followed by the address of the next node; the last one's link is 0. The program follows the links, adding up the values.
- Watch `a1` jump from node to node: the next address isn't known until the current node has been loaded, so each step waits for memory.
:::

```sim cpu
.data
n1: .word 5, n2
n3: .word 9, 0
n2: .word 7, n3
.text
    la   a1, n1           # head of the list
    li   a0, 0            # sum
loop:
    beqz a1, done         # a null link ends the list
    lw   t0, 0(a1)        # node's value
    add  a0, a0, t0
    lw   a1, 4(a1)        # node's link: the next node's address
    j    loop
done:
    ebreak
show: a0, a1, t0
hex: a1
memory: 0x1000..0x1018
speed: 2
```

::: predict
## A linked-list node holds one 4-byte int and a 4-byte pointer. The allocator adds an 8-byte header to every block and rounds sizes up to multiples of 8. What fraction of the heap memory used by a list holds the actual ints?

- [ ] 50%
- [x] 25%
- [ ] 67%
- [ ] 100%

::: reveal
Each node is 8 bytes of payload, plus 8 bytes of header: 16 bytes per node, of which 4 are the int. A quarter of the memory is data, a quarter is links, and half is the allocator's bookkeeping. Small objects on a general-purpose heap are expensive, which is why embedded code often allocates from fixed pools or arrays instead.
:::
:::

::: nameit
## The heap

A program's memory has a fixed region for code and globals, the stack (lesson 14) for function calls, and the heap for everything allocated at run time. `malloc(n)` finds a free block of at least $n$ bytes and returns its address; `free(p)` gives it back.

- **Alignment:** blocks are aligned so any type fits, typically to 8 or 16 bytes, so sizes round up.
- **Headers:** most allocators store the block's size just before it, so `free` knows how much to return: often 8 bytes per block.
- **Free lists:** freed blocks are linked into lists, searched by the next `malloc`, and merged with free neighbors (**coalescing**).
- **Bump allocation:** the simplest allocator just advances a pointer, $p \leftarrow p + \text{round}(n)$, and never frees, which is ideal for memory allocated once at start-up.

## Linked lists

A node is a struct holding data and a pointer to the next node, with 0 (`NULL`) marking the end. Inserting or removing in the middle only changes two links, with no copying, unlike an array. Finding the $k$th element takes $k$ dependent loads, and each load must finish before the next address is known. A cache miss costs tens to hundreds of cycles (lesson 44), so walking a list scattered through memory can be a hundred times slower than scanning an array of the same values.

## What goes wrong

- **Leaks:** allocated blocks whose last pointer is lost can never be freed. A long-running device slowly runs out of memory.
- **Use after free and double free:** using or freeing a block twice corrupts the allocator's lists.
- **Fragmentation:** after many allocations and frees of mixed sizes, plenty of memory can be free in total while no single free block is big enough. Embedded systems avoid it with fixed-size pools.
:::

::: example
## A bump allocator starts at 0x2000 with 8-byte alignment and no headers. A program allocates 12, 20 and 5 bytes. What addresses does it get, and where does the next free byte sit?

::: solution
1. **The first block.** 12 rounds to 16: the block is 0x2000 to 0x200F.
2. **The second block.** 20 rounds to 24: it starts at 0x2010 and ends at 0x2027.
3. **The third block.** 5 rounds to 8: it starts at 0x2028.
4. **The next free byte.** 0x2030.
5. **The padding.** 37 requested bytes used 48, 23% of it padding.

**Answer:** the blocks start at 0x2000, 0x2010 and 0x2028, and the next free byte is at 0x2030.
:::
:::

::: example
## A list of 1000 nodes, each an int and a pointer, is built with a malloc that adds an 8-byte header and rounds to 8. Compare its memory with an array of 1000 ints, and the time to sum each if every list node costs a 100-cycle cache miss while the array streams at one int per cycle.

::: solution
1. **The list's memory.**
   $$1000 \times 16 = 16\,000\ \text{bytes}$$
2. **The array's memory.** 4000 bytes, a quarter.
3. **Summing the array.** About 1000 cycles.
4. **Summing the list.**
   $$1000 \times 100 = 100\,000\ \text{cycles}$$
   a hundred times longer, because each address depends on the previous load and the processor can't fetch ahead.
5. **In practice.** When the items are allocated one after another, they often land next to each other and the misses mostly disappear, which is why benchmarks of lists vary so much.

**Answer:** the list takes 16 000 bytes against the array's 4000, and about 100 000 cycles to sum against 1000.
:::
:::

::: example
## A 1024-byte heap is filled with sixteen 64-byte blocks. Every second one is freed. How much is free, and what's the largest block `malloc` could now return?

::: solution
1. **Free memory.** Eight blocks are free: 512 bytes in total.
2. **The largest block.** No two free blocks are adjacent, so they can't coalesce, and the largest request that can succeed is 64 bytes.
3. **What it means.** A request for 100 bytes fails with half the heap free. That's external fragmentation, and it's why safety-critical embedded code often bans `malloc` after start-up.

**Answer:** 512 bytes are free, but the largest block `malloc` can return is 64 bytes.
:::
:::

::: check
given: n = 3 | 9 | 13 | 21 | 37; a = 8 | 16
answer: a*ceil(n/a)
unit: B
tolerance: 0.5%

## A bump allocator aligns to {a} bytes. How much space does a request for {n} bytes take?

::: right
Right. Round {n} up to a multiple of {a}: {answer}.
:::

::: misses
- [n] Requests round up to the alignment.
- [a*floor(n/a)] Round up, not down: the block must hold all {n} bytes.
- [any] Not yet. $a\lceil n/a\rceil$.
:::
:::

::: check
kind: parts
given: d = 4 | 8 | 12; h = 8 | 16; a = 8 | 16

## A node holds {d} bytes of data and a 4-byte pointer. The allocator adds an {h}-byte header and rounds the total to a multiple of {a}.

::: part
answer: a*ceil((d + 4 + h)/a)
unit: B
tolerance: 0.5%

### How many bytes does each node use?

::: misses
- [d + 4] Include the header and the rounding.
- [any] Not yet. Round $d + 4 + h$ up to a multiple of {a}.
:::
:::

::: part
answer: d/(a*ceil((d + 4 + h)/a))*100
tolerance: 0.5%

### What percentage of that is the data itself?

::: misses
- [(d + 4)/(a*ceil((d + 4 + h)/a))*100] The pointer is overhead too; count only the data.
- [any] Not yet. Data bytes over total bytes.
:::
:::

::: right
Right. Small nodes spend most of their memory on bookkeeping.
:::
:::

::: check
given: n = 100 | 1000 | 10000; m = 50 | 100 | 300
answer: m
tolerance: 0.5%

## Summing a {n}-node linked list costs a {m}-cycle cache miss per node; summing an array of the same {n} values costs one cycle per value. How many times longer does the list take?

::: right
Right: {answer} times, since every load waits for the one before.
:::

::: misses
- [n*m] That's the list's cycle count. Divide by the array's.
- [any] Not yet. $nm$ cycles against $n$.
:::
:::

::: check
given: B = 32 | 64 | 128; N = 16 | 32
answer: N/2*B
unit: B
tolerance: 0.5%

## A heap is filled with {N} blocks of {B} bytes, and every second block is freed. How much memory is free in total?

::: right
Right: {answer}, though no free block is larger than {B} bytes.
:::

::: misses
- [N*B] Only half the blocks were freed.
- [B] That's the largest single free block, not the total.
- [any] Not yet. Half the blocks, each {B} bytes.
:::
:::

::: check
kind: asm
given: v1 = 1..100 int; v2 = 1..100 int; v3 = 1..100 int
expect: a0 = 3

## Three nodes are built at 0x1000, 0x1010 and 0x1008 (value, then link), linked in that order and ending with a 0 link. Starting from the head at 0x1000, count the nodes into a0 by following the links.

```asm starter
    li t0, 0x1000
    li t1, v1
    sw t1, 0(t0)
    li t1, 0x1010
    sw t1, 4(t0)
    li t1, v2
    sw t1, 16(t0)
    li t1, 0x1008
    sw t1, 20(t0)
    li t1, v3
    sw t1, 8(t0)
    sw zero, 12(t0)
    li a1, 0x1000
    # your code: count the nodes into a0
    li a0, 0
    ebreak
```

```asm solution
    li t0, 0x1000
    li t1, v1
    sw t1, 0(t0)
    li t1, 0x1010
    sw t1, 4(t0)
    li t1, v2
    sw t1, 16(t0)
    li t1, 0x1008
    sw t1, 20(t0)
    li t1, v3
    sw t1, 8(t0)
    sw zero, 12(t0)
    li a1, 0x1000
    li a0, 0
loop:
    beqz a1, done
    addi a0, a0, 1
    lw a1, 4(a1)
    j loop
done:
    ebreak
```

::: right
Right. The nodes aren't in address order; only the links say which comes next.
:::
:::

::: check
kind: choice

## A data logger mallocs a 64-byte record for each reading, frees records after uploading them, and after a week `malloc` starts failing although the heap is half empty. What's the most likely cause?

- [x] Fragmentation: mixed allocations have left free memory in pieces too small or scattered for the requests
- [ ] The heap's header bytes have filled the memory
- [ ] The stack has overflowed into the heap
- [ ] The processor's cache is full

::: right
Right. Free memory split into many small, non-adjacent pieces can't satisfy a request that needs one contiguous block. A fixed pool of 64-byte records, allocated once, can't fragment.
:::

::: misses
- [2] Headers are freed with their blocks.
- [3] A stack overflow would corrupt data or crash, not make malloc fail with free memory.
- [4] The cache holds copies of memory; it doesn't limit allocation.
:::
:::

::: check
kind: python
given: H = 1024 | 4096; seed = 1 | 2 | 3

## Write a first-fit allocator over a heap of `H` = {H} bytes. `alloc(n)` rounds `n` up to 8, finds the lowest-addressed free block big enough, splits it, and returns the address (or `None`); `release(addr)` frees the block and merges it with free neighbors. Keep blocks as a sorted list of `[addr, size, free]`. Then run the workload: with `rng = random.Random(seed)`, repeat 500 times: if `rng.random() < 0.6`, allocate `rng.randrange(8, 129)` bytes (record successes), else free a random live block (`rng.randrange(len(live))`, removing it from the list) if any. Set `failures` (failed allocations) and `largest` (the largest free block at the end).

```python starter
import random
failures = 0
largest = H
```

```python solution
import random
blocks = [[0, H, True]]
def alloc(n):
    n = (n + 7) // 8 * 8
    for i, (a, s, f) in enumerate(blocks):
        if f and s >= n:
            if s > n:
                blocks.insert(i + 1, [a + n, s - n, True])
            blocks[i] = [a, n, False]
            return a
    return None
def release(addr):
    i = next(k for k, b in enumerate(blocks) if b[0] == addr)
    blocks[i][2] = True
    if i + 1 < len(blocks) and blocks[i + 1][2]:
        blocks[i][1] += blocks[i + 1][1]; del blocks[i + 1]
    if i > 0 and blocks[i - 1][2]:
        blocks[i - 1][1] += blocks[i][1]; del blocks[i]
rng = random.Random(seed)
live, failures = [], 0
for _ in range(500):
    if rng.random() < 0.6:
        a = alloc(rng.randrange(8, 129))
        if a is None: failures += 1
        else: live.append(a)
    elif live:
        release(live.pop(rng.randrange(len(live))))
largest = max([s for a, s, f in blocks if f], default=0)
```

```python tests
import random
def run():
    bl = [[0, H, True]]
    def al(n):
        n = (n + 7) // 8 * 8
        for i, (a, s, f) in enumerate(bl):
            if f and s >= n:
                if s > n: bl.insert(i + 1, [a + n, s - n, True])
                bl[i] = [a, n, False]; return a
        return None
    def rl(addr):
        i = next(k for k, b in enumerate(bl) if b[0] == addr)
        bl[i][2] = True
        if i + 1 < len(bl) and bl[i + 1][2]: bl[i][1] += bl[i + 1][1]; del bl[i + 1]
        if i > 0 and bl[i - 1][2]: bl[i - 1][1] += bl[i][1]; del bl[i]
    rng = random.Random(seed); live, fails = [], 0
    for _ in range(500):
        if rng.random() < 0.6:
            a = al(rng.randrange(8, 129))
            if a is None: fails += 1
            else: live.append(a)
        elif live: rl(live.pop(rng.randrange(len(live))))
    return fails, max([s for a, s, f in bl if f], default=0)
f, l = run()
assert (failures, largest) == (f, l), f"Expected {f} failures and a largest free block of {l} bytes."
```

::: right
Right. Failures begin while plenty of memory is free in total: the signature of fragmentation.
:::
:::

::: explain
## A linked list and an array hold the same 10 000 sensor readings. Explain why summing the list can be far slower, even though both execute about the same number of add instructions.

::: model
In the array, the address of each element is known in advance, the elements sit next to each other, and the hardware fetches whole cache lines and prefetches the next ones, so the loads stream at about one per cycle. In the list, each node's address is stored in the previous node, so the processor can't start loading node k + 1 until node k's load has finished: the loads form a dependent chain. If the nodes are scattered through memory, nearly every one is a cache miss costing a hundred cycles or more, and the out-of-order hardware can't overlap them because it doesn't know the addresses yet. The instruction count is similar; the memory behavior differs by orders of magnitude.
:::
:::

::: practice

::: check
given: n = 5 | 17 | 30; a = 4 | 8
answer: a*ceil(n/a)
unit: B
tolerance: 0.5%

## With {a}-byte alignment, how many bytes does a {n}-byte request occupy?

::: misses
- [n] Round up to the alignment.
- [any] $a\lceil n/a\rceil$.
:::
:::

::: check
given: d = 4 | 16; h = 8 | 16
answer: d/(d + 4 + h)*100
tolerance: 0.5%

## Nodes hold {d} bytes of data, a 4-byte link and an {h}-byte header (sizes already aligned). What percentage is data?

::: misses
- [(d + 4)/(d + 4 + h)*100] The link isn't data.
- [any] Data over the whole node.
:::
:::
:::
