C8 · Lesson 12 · Dynamic memory and linked structures
The heap, what malloc costs, and following pointers through memory
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.
- 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
a1jump from node to node: the next address isn't known until the current node has been loaded, so each step waits for memory.
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?
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.
Name it
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 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
freeknows 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, , 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 th element takes 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.
Worked 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?
Show the solution
- The first block. 12 rounds to 16: the block is 0x2000 to 0x200F.
- The second block. 20 rounds to 24: it starts at 0x2010 and ends at 0x2027.
- The third block. 5 rounds to 8: it starts at 0x2028.
- The next free byte. 0x2030.
- 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.
Worked 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.
Show the solution
- The list's memory.
- The array's memory. 4000 bytes, a quarter.
- Summing the array. About 1000 cycles.
- Summing the list. a hundred times longer, because each address depends on the previous load and the processor can't fetch ahead.
- 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.
Worked 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?
Show the solution
- Free memory. Eight blocks are free: 512 bytes in total.
- The largest block. No two free blocks are adjacent, so they can't coalesce, and the largest request that can succeed is 64 bytes.
- 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
mallocafter start-up.
Answer 512 bytes are free, but the largest block malloc can return is 64 bytes.
Check
A bump allocator aligns to 8 bytes. How much space does a request for 9 bytes take?
Check
A node holds 8 bytes of data and a 4-byte pointer. The allocator adds an 8-byte header and rounds the total to a multiple of 16.
(a)
How many bytes does each node use?
(b)
What percentage of that is the data itself?
Check
Summing a 1000-node linked list costs a 50-cycle cache miss per node; summing an array of the same 1000 values costs one cycle per value. How many times longer does the list take?
Check
A heap is filled with 16 blocks of 64 bytes, and every second block is freed. How much memory is free in total?
Check
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.
RISC-V RV32IM (base integer plus multiply and divide). End your program with ebreak. Tab indents; press Esc and then Tab to move on.
Check
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?
Check
Write a first-fit allocator over a heap of H = 1024 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 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Explain why
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.
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
Keep practicing
8 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.