Chapter 18: C
C is the language in which every other runtime in this book is ultimately written, and it is the one that forgives nothing. Memory is yours to allocate and yours to free; there is no garbage collector, no bounds check, and no type system strong enough to stop a void * from being misread. A mistake does not throw an exception. It is undefined behaviour, which may work perfectly on your machine and corrupt the heap on someone else’s. Working in C teaches you what the higher-level languages are doing for you, and what it costs.
Concepts from other sections (15)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Intrusive list: a list whose link fields are embedded in the elements themselves rather than in separately allocated nodes. Read more: 18.3 Intrusive linked list
- Thread pool: a fixed set of long-lived worker threads that execute tasks taken from a shared queue. Read more: 18.7 Thread pool
- Arena (bump) allocator: an allocator that serves requests by advancing an offset and frees all allocations at once. Read more: 18.8 Arena allocator
- Dangling pointer: a pointer to memory that has been freed or moved, which is undefined behaviour to dereference. Read more: 18.1 Dynamic array
- Opaque type: a Scala 3 type alias whose underlying representation is visible only where it is defined, giving a distinct type with no run-time cost; a newtype without a wrapper. Read more: Chapter 25: Scala
- Binary heap: a complete binary tree in an array in which no child comes out before its parent. Read more: 15.6 A binary heap with lazy deletion
- Incremental parser: a parser that accepts input in arbitrary chunks and resumes where the previous chunk ended. Read more: 18.10 HTTP request parser
- Linear probing: on collision, trying the next slot, then the next, wrapping at the end. Read more: 18.2 Hash map with open addressing
- Tombstone: a marker left by deletion that lookups skip over and inserts may reuse. Read more: 18.2 Hash map with open addressing
- Load factor: the fraction of slots that are not empty; here it counts tombstones as well as live entries. Read more: 18.2 Hash map with open addressing
- Heapify (Floyd’s method): building a heap in O(n) by sifting down every internal node from the bottom up. Read more: 18.4 Binary heap
- Stable sort: a sort that keeps equal elements in their input order; heapsort is not one. Read more: 18.4 Binary heap
- Depth-first search (DFS): traversal that follows one path as far as possible before backtracking, using a stack. Read more: 18.6 Graph as an adjacency list
- Condition variable: a primitive that lets a thread sleep until another thread signals that shared state may have changed. Read more: 18.7 Thread pool
- bump allocation: allocating by advancing an offset past padding and the request, with no per-allocation bookkeeping. Read more: 22.1 C runtime support and an arena allocator with marks in AI Engineering
This chapter is ten classic exercises, each with a reference implementation and a full walkthrough. The arc runs from single containers (a growable array, a hash map, an intrusive list, a heap) through algorithms on them (merge sort, graph traversal) to the runtime pieces that larger systems are made of: a thread pool, an arena allocator, a string interner, and an incremental HTTP parser. Each section states the problem and its constraints, builds the design up from first principles, walks through the key code with annotations, explains why this design beats the obvious alternatives, and ends with review questions that check you can explain the solution back.
Learning objectives
- Manage heap memory in C without leaks, double frees, or dangling pointers, and verify it with AddressSanitizer and UndefinedBehaviorSanitizer.
- Design C interfaces with opaque types, explicit error returns, and clear ownership rules.
- Implement and analyse the core systems data structures (dynamic array, open-addressing hash map, intrusive list, binary heap, adjacency-list graph).
- Build the runtime pieces of a server: a pthreads thread pool, an arena allocator, a string interner, and an incremental parser.
- Explain, for each design, which alternatives were rejected and why.
Before you begin
Section titled “Before you begin”You should be able to write and compile a small C program, and know what a pointer, a struct, and malloc are. If any of that is shaky, read C: memory, pointers, structs, headers, and the C11 toolchain in Programming and Algorithms first. The big-O arguments assume the basics of asymptotic analysis.
The language in brief
Section titled “The language in brief”C’s memory model is manual: you allocate with malloc and release with free, locals live on the stack and everything else on the heap, and there is no garbage collector. The type system is static but weak. Implicit conversions are everywhere, and generic code goes through void *, which the compiler cannot check. Errors are reported through return codes and errno; setjmp and longjmp exist but are best avoided. Concurrency comes from pthreads and, since C11, stdatomic.h, with nothing at the language level for asynchronous work. You build with gcc or clang, usually under make or cmake, with interfaces in headers and implementations in source files. The exercises use C11, which is preferred here; C17 also works.
Idioms to practise
Section titled “Idioms to practise”- Opaque pointers for encapsulation: declare
struct Foo;in the header and define it only in the.cfile. - The goto-cleanup pattern for releasing resources on every exit path.
- Flexible array members for variable-length structs.
static inlinefunctions in headers for zero-cost abstractions.- Compound literals for temporary struct values.
- Designated initializers for readable struct initialization.
Building and running the exercises
Section titled “Building and running the exercises”Each exercise directory holds a header (the interface), the reference implementation, a main.c test suite, and the walkthrough. Every solution uses only the C standard library, plus pthreads for the thread pool. To build and run one, compile its sources together from its directory:
cd practice/build/systems/c/01-dynamic-arraycc -std=c11 -Wall -Wextra -O2 *.c -o vec && ./vecThe test program prints ok ... and exits 0 when every check holds. The thread pool needs -pthread and ships a run.sh that adds it. Running just run-practice-solutions from the repository root builds and runs all ten.
In this chapter
Section titled “In this chapter”The exercises are ordered by concept, not by difficulty, so if you are choosing where to start, the difficulty rating (1 is easiest, 5 hardest) is a better guide than the number.
- Dynamic array (difficulty 2). A growable array of
intthat teaches whyreallocis dangerous, why the growth factor must be geometric, and how to survive allocation failure. The longer treatment is A growable array in Programming and Algorithms. - Hash map with open addressing (difficulty 3). String keys, linear probing, tombstones, and a load factor that counts the dead. It is the baseline that A Swiss table improves on.
- Intrusive linked list (difficulty 2). The Linux-kernel list: the links live inside your struct, and
container_ofwalks back from the link to the object. Compare An intrusive list and an LRU. - Binary heap (difficulty 2). A priority queue in a flat array, with
sift_up,sift_down, and linear-time heapify. Heap top-k in C puts it to work. - Merge sort, buffered and in place (difficulty 2). Two stable sorts that trade memory for time: one with a scratch buffer, one with rotations.
- Graph as an adjacency list (difficulty 3). Growable per-vertex arrays, breadth-first and depth-first search, and topological sort.
- Thread pool (difficulty 4). pthreads, condition variables, a work queue, and a shutdown that drains cleanly. Thread pool and tl_parallel_for in AI Engineering uses the same design.
- Arena allocator (difficulty 3). Bump allocation, alignment, and freeing everything at once. C runtime support and an arena allocator with marks extends it.
- String interning (difficulty 3). A hash table that hands out stable addresses, so string equality becomes pointer equality.
- HTTP request parser (difficulty 4). A state machine that consumes input incrementally, in whatever chunks the network delivers.
Key terms
Section titled “Key terms”- Opaque pointer: a pointer to a struct that a header only declares (
struct Foo;) and the.cfile defines, so callers can hold and pass it but cannot reach its fields; C’s main tool for encapsulation. - Goto-cleanup pattern: a C idiom in which every failure path jumps with
gototo labels at the end of the function that release resources in reverse order of acquisition, so each resource is freed exactly once on every exit path.
Further reading
Section titled “Further reading”- C11 standard draft (N1570): free.
- cppreference.com/w/c: the best online reference.
- The C Programming Language by Kernighan and Ritchie, 2nd edition: the classic.
- Modern C by Jens Gustedt: free PDF.
- Expert C Programming by Peter van der Linden: deep dives.