C812 of 55
0 XP
  1. Hook
  2. Play
  3. Predict
  4. Name it
  5. Check
  6. Explain

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

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?

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 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←p+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 kth 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.

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

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
  1. The list's memory. 1000×16=16000bytes
  2. The array's memory. 4000 bytes, a quarter.
  3. Summing the array. About 1000 cycles.
  4. Summing the list. 1000×100=100000cycles 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.

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

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.

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.