Programming notes · chapters 1–12

120 editable diagrams

Clear visual explanations of memory, control flow, operating systems, networks, concurrency, and programming languages. Open any diagram at full size, or save its SVG and edit it in Inkscape.

1. Foundations / 10 diagrams

One address, one selected memory location
Notes 1.1.2

One address, one selected memory location

Read and write transactions select the same addressed byte but reverse the data direction.

A binary numeral is a weighted sum
Notes 1.3.2

A binary numeral is a weighted sum

The same value is decomposed into binary weights and reconstructed by repeated division.

Byte order changes placement, not the value
Notes 1.4.2

Byte order changes placement, not the value

Little-endian and big-endian store the same four-byte number at increasing addresses.

Where translation and execution happen
Notes 1.4.7

Where translation and execution happen

Compiled, interpreted and bytecode execution place translation and the runtime at different stages.

Two paths, one directory-tree destination
Notes 1.2.5

Two paths, one directory-tree destination

Absolute paths begin at root; relative paths start at the current working directory.

The instruction pointer controls the next step
Notes 1.1.3

The instruction pointer controls the next step

Fetch advances the instruction pointer; a taken jump replaces its value.

Permission bits form three octal digits
Notes 1.2.13

Permission bits form three octal digits

Owner, group and other permission triplets map read, write and execute to weights 4, 2 and 1.

From command text to argument strings
Notes 1.2.6, 1.2.7

From command text to argument strings

Quoting preserves a single argument while an unquoted filename pattern expands into matching names.

Standard streams are independent routes
Notes 1.2.11

Standard streams are independent routes

A pipeline joins output to input, while diagnostics have their own route.

The same bits have two interpretations
Notes 1.4.2

The same bits have two interpretations

A four-bit wheel shows modular arithmetic and the signed boundary; negation inverts and adds one.

2. Pascal and data structures / 10 diagrams

Index an array; name a record field
Notes 2.6.4, 2.6.5

Index an array; name a record field

An array has homogeneous indexed components; a record has named fields that can have different types.

Assignment replaces a stored value
Notes 2.2.2, 2.2.8

Assignment replaces a stored value

A three-step swap preserves the first value in temporary storage before overwriting it.

Search chooses one subtree at each comparison
Notes 2.11.5

Search chooses one subtree at each comparison

A search for an absent value ends at the null child link where insertion can attach a node.

Hanoi splits one task into three tasks
Notes 2.11.2

Hanoi splits one task into three tasks

Move the smaller tower away, move the largest disk, then move the smaller tower onto it.

A pointer to the incoming link unifies deletion
Notes 2.10.6

A pointer to the incoming link unifies deletion

The cursor identifies a pointer cell, so deletion updates either the head or a predecessor link by the same operation.

Prepend without losing the old list
Notes 2.10.4

Prepend without losing the old list

Allocate and initialize a new node, link it to the old head, then replace the head pointer.

Test before the body or after it
Notes 2.2.10, 2.2.11

Test before the body or after it

While can execute zero times; repeat always executes its body before testing its termination condition.

Recursive calls postpone work until return
Notes 2.3.7

Recursive calls postpone work until return

Printing digits after the recursive call uses suspended frames to restore their original order.

One arrival sequence, two removal orders
Notes 2.10.5

One arrival sequence, two removal orders

Stack operations use one end; queue insertion and removal use opposite ends.

Copy a value or name the caller storage
Notes 2.3.4

Copy a value or name the caller storage

Value parameters have independent local storage; variable parameters denote the original variable.

3. Assembly / 10 diagrams

Multiply widens; divide splits the result
Notes 3.2.8

Multiply widens; divide splits the result

The one-operand i386 forms use EDX:EAX as a double-width product or dividend.

Effective address combines three terms
Notes 3.2.5

Effective address combines three terms

A matrix element address combines its base, row displacement and scaled column index; LEA only computes it.

Macro expansion happens before program execution
Notes 3.5.1, 3.5.2

Macro expansion happens before program execution

A macro call expands to push, call and cleanup instructions; the CPU runs the resulting instructions.

Copy backward when the destination overlaps above
Notes 3.2.13

Copy backward when the destination overlaps above

A forward overlapping copy destroys unread input; backward order preserves it.

Register names overlap the same bits
Notes 3.2.1

Register names overlap the same bits

EAX, AX, AH and AL select nested or adjacent portions of one 32-bit register.

The comparison is the same; the chosen flags differ
Notes 3.2.7, 3.2.9

The comparison is the same; the chosen flags differ

CMP sets flags from subtraction, and signed and unsigned branches interpret them differently.

EBP anchors one invocation while ESP moves
Notes 3.3.5, 3.3.6, 3.3.7

EBP anchors one invocation while ESP moves

Arguments, return address, saved frame pointer and locals occupy fixed offsets in an i386 frame.

An unresolved symbol pulls in an archive member
Notes 3.7.5

An unresolved symbol pulls in an archive member

Resolving one reference can introduce another dependency while unused archive members remain excluded.

A syscall enters through an OS-defined gate
Notes 3.6.4, 3.6.5

A syscall enters through an OS-defined gate

The historical Linux i386 int 80h ABI carries a write request into a privileged handler and returns a result.

x87 pushes change TOP, not every stored value
Notes 3.8.2, 3.8.3

x87 pushes change TOP, not every stored value

Physical register contents stay in place while logical ST names rotate with TOP.

4. C / 10 diagrams

Reallocation must preserve the original pointer
Notes 4.3.14; 4.10.1

Reallocation must preserve the original pointer

For a positive new size, a failed realloc leaves the original allocation valid.

Inorder traversal: left, node, right
Notes 4.5.4

Inorder traversal: left, node, right

Recursion stores the return position; an explicit stack must store it as data.

A callback combines reusable traversal with private state
Notes 4.9.3

A callback combines reusable traversal with private state

The service passes userdata unchanged; the callback knows its actual type.

Delete a node by changing its incoming link
Notes 4.5.2; 4.9.2

Delete a node by changing its incoming link

A pointer-to-pointer works for both the head and a next field inside a node.

A pointer to a literal is not a character array
Notes 4.3.19

A pointer to a literal is not a character array

Initialization can create a separate mutable array or an address of literal storage.

Declarations compile; definitions link
Notes 4.7.1; 4.7.2; 4.7.3

Declarations compile; definitions link

The implementation includes its own public header so the compiler can check both sides.

A C string ends at its first zero byte
Notes 4.3.18

A C string ends at its first zero byte

Storage capacity, string length, and binary data length are different quantities.

Structure layout includes padding
Notes 4.5.1

Structure layout includes padding

One illustrative ABI: char alignment 1, int alignment 4; actual layout is implementation-dependent.

5. Operating-system services / 10 diagrams

File descriptors are references, not file positions
Notes 5.2.3; 5.3.4

File descriptors are references, not file positions

dup and fork can create several descriptor references to one open-file description.

Termination and reaping are separate events
Notes 5.3.6; 5.3.7

Termination and reaping are separate events

A zombie has finished executing; it retains status until the parent collects it.

fork creates a process; exec replaces its program
Notes 5.3.4; 5.3.5

fork creates a process; exec replaces its program

Parent and child continue independently after fork. A successful exec never returns to the old program.

Mapped addresses provide another view of file bytes
Notes 5.2.7

Mapped addresses provide another view of file bytes

MAP_SHARED and MAP_PRIVATE differ when a process writes through a mapping.

Names lead to inodes; open files can outlive names
Notes 5.2.1

Names lead to inodes; open files can outlive names

Hard links share an inode. A symbolic link stores a pathname of its own.

Pipe EOF depends on every writer reference
Notes 5.3.15

Pipe EOF depends on every writer reference

A reader first drains buffered bytes; it sees EOF only after the last write end closes.

Redirection rewires a descriptor before exec
Notes 5.3.10

Redirection rewires a descriptor before exec

The new program still writes to descriptor 1; the shell chooses what descriptor 1 refers to.

Check and wait must be one atomic handoff
Notes 5.3.14

Check and wait must be one atomic handoff

Blocking a signal preserves an early notification until sigsuspend temporarily unblocks it.

A terminal targets its foreground process group
Notes 5.4.2

A terminal targets its foreground process group

A session contains groups; a foreground pipeline is one job even when it has several processes.

6. Networks / 10 diagrams

Datagrams preserve boundaries; streams preserve byte order
Notes 6.2.4; 6.3.3; 6.3.4

Datagrams preserve boundaries; streams preserve byte order

The sizes returned by TCP reads need not match the sizes of the sender’s writes.

DNS distributes authority through a name hierarchy
Notes 6.2.6

DNS distributes authority through a name hierarchy

The resolver queries each authority. Dashed links show delegation; cached answers can skip this path.

Each lower layer carries the unit above it
Notes 6.2.1; 6.2.3

Each lower layer carries the unit above it

An IP packet crosses different links; each hop uses the frame format appropriate to that link.

Network byte order is most significant byte first
Notes 6.2.3; 6.3.2

Network byte order is most significant byte first

Conversions preserve the numeric value while choosing the byte representation required by the protocol.

One server port supports many connected sockets
Notes 6.2.4; 6.3.4

One server port supports many connected sockets

A connection is distinguished by both endpoints, not by the server port alone.

The longest matching prefix selects the route
Notes 6.1.2; 6.2.3

The longest matching prefix selects the route

A default route matches every IPv4 destination; a more specific matching route takes priority.

Wait for readiness, then do bounded work
Notes 6.4.3; 6.4.4

Wait for readiness, then do bounded work

Rebuild descriptor sets every iteration; select overwrites them with the ready subsets.

A listener and its accepted sockets have different jobs
Notes 6.3.4

A listener and its accepted sockets have different jobs

accept returns another descriptor, leaving the listening socket ready for further connection requests.

Frame complete lines before advancing the session
Notes 6.4.5

Frame complete lines before advancing the session

Keep a separate input buffer and dialogue state for every connected client.

Connection establishment exchanges sequence numbers
Notes 6.2.4; 6.3.4

Connection establishment exchanges sequence numbers

Simplified successful TCP opening: the handshake is transport setup, before application dialogue.

7. Concurrency / 12 diagrams

Testing and claiming must be one operation
Notes 7.1.3; 7.1.5

Testing and claiming must be one operation

Separate test/store lets two threads enter; an atomic exchange grants only one owner.

A haircut needs both admission and completion signals
Notes 7.2.5

A haircut needs both admission and completion signals

Four semaphore handshakes coordinate a waiting client, work-chair preparation and completion.

Reserve the buffer resource before taking its mutex
Notes 7.2.1

Reserve the buffer resource before taking its mutex

Correct producer/consumer ordering permits progress; waiting for space while holding the mutex deadlocks a full buffer.

Lock the whole invariant
Notes 7.1.2

Lock the whole invariant

A transfer protects both reads and writes; a report can compute privately after a consistent copy.

File-lock lifetime follows its ownership model
Notes 7.4.3; 7.4.4; 7.4.5

File-lock lifetime follows its ownership model

BSD-style flock belongs to an open file description; traditional POSIX record locks belong to a process and file.

A read-only scan can still race
Notes 7.1.1

A read-only scan can still race

A summation mixes destination-before-transfer with source-after-transfer and loses the transferred amount.

Peterson: the last contender yields
Notes 7.1.3

Peterson: the last contender yields

With both intent flags true, the last store to who_waits selects the waiting participant.

A full pipe can turn wait-before-read into deadlock
Notes 7.2.2

A full pipe can turn wait-before-read into deadlock

Parent waits for child termination while the child is blocked writing to a full pipe that only the parent can drain.

Reader overlap can keep a writer waiting
Notes 7.2.4

Reader overlap can keep a writer waiting

Continuous reader cohorts can starve a writer; an admission gate prevents new readers extending the current cohort.

A global lock order breaks circular wait
Notes 7.2.2; 7.2.3

A global lock order breaks circular wait

Opposing resource orders form a deadlock cycle; requiring lower then higher removes that possibility.

A semaphore counts unclaimed permits
Notes 7.1.6

A semaphore counts unclaimed permits

Two permits are consumed; a third participant waits until a posted permit can be consumed.

8. Inside the kernel / 12 diagrams

A buffer can combine writes and satisfy reads
Notes 8.4.6

A buffer can combine writes and satisfy reads

A cached block is updated twice and read between updates; only the latest dirty version need be physically written.

A context switch changes which saved state runs
Notes 8.2.1; 8.3.3

A context switch changes which saved state runs

The scheduler saves task A registers, selects task B and restores its execution state and address-space context.

A recoverable page fault restarts the instruction
Notes 8.3.2; 8.3.5

A recoverable page fault restarts the instruction

Access to a valid nonresident page faults; the kernel obtains the page, installs the mapping and resumes the faulting instruction.

Virtual contiguity does not imply physical contiguity
Notes 8.4.10; 8.3.5

Virtual contiguity does not imply physical contiguity

Four adjacent virtual pages map to nonadjacent physical frames, so a simple contiguous DMA range cannot describe them.

Three causes of entry into the kernel
Notes 8.1; 8.1.1

Three causes of entry into the kernel

System calls, exceptions, and hardware interrupts cross the privilege boundary for different reasons.

Paging uses scattered free frames
Notes 8.3.1; 8.3.3; 8.3.5

Paging uses scattered free frames

A contiguous allocation can fail despite sufficient total free memory; paging maps adjacent virtual pages to separate free frames.

Interrupts allow useful CPU work while a device runs
Notes 8.4.5

Interrupts allow useful CPU work while a device runs

A timeline contrasts repeated status polling with device operation overlapping another runnable task.

I/O completion makes a task ready, not immediately running
Notes 8.2.1; 8.2.2; 8.4.5

I/O completion makes a task ready, not immediately running

A blocked task becomes runnable on I/O completion, then waits until the scheduler selects it.

Shared storage can split on a private write
Notes 8.3.1; 8.3.5

Shared storage can split on a private write

Conceptual copy-on-write sharing maps two address spaces to one frame until a private writer needs its own copy.

Signal delivery temporarily redirects user execution
Notes 8.2.3

Signal delivery temporarily redirects user execution

The kernel saves user context in a signal frame, runs the handler and restores the interrupted context through sigreturn.

A TLB caches translations, not program data
Notes 8.3.5

A TLB caches translations, not program data

Virtual page number is translated through a cached entry or page table; the offset is preserved.

One path can cross into another filesystem
Notes 8.4.8

One path can cross into another filesystem

Pathname lookup follows the common directory tree and crosses a mount point into the mounted filesystem root.

9. Programming paradigms / 6 diagrams

A callback separates registration from invocation
Notes 9.4.1

A callback separates registration from invocation

The application describes an action now; an event source invokes it later.

Metaprogramming has two separate executions
Notes 9.4.3

Metaprogramming has two separate executions

The generator runs to produce a program; the generated program runs to solve the task.

A fold chooses the nesting of operations
Notes 9.2.3

A fold chooses the nesting of operations

Subtraction exposes the difference: changing the fold direction changes the expression.

Explicit state turns chunks into complete lines
Notes 9.4.2; 10.10

Explicit state turns chunks into complete lines

A byte stream can end a read anywhere, including in the middle of one logical message.

Recursion remembers the route through a tree
Notes 9.2.1

Recursion remembers the route through a tree

In-order traversal: finish the left subtree, visit the node, then finish the right subtree.

10. C++ and object lifetimes / 12 diagrams

An abstract data type protects a representation invariant
Notes 10.3.4; 10.8.2

An abstract data type protects a representation invariant

Example: a buffer must always satisfy 0 <= size <= capacity.

One event selector dispatches many client sessions
Notes 10.10

One event selector dispatches many client sessions

Descriptor readiness selects a handler; each session retains its own partially received line.

Construction order also defines destruction order
Notes 10.4.15; 10.6.4

Construction order also defines destruction order

For this single-base class, member declaration order controls initialization.

Initialization and assignment start from different states
Notes 10.4.10; 10.4.18

Initialization and assignment start from different states

The syntax looks similar, but only assignment replaces the value of an existing object.

Stack unwinding releases fully constructed local owners
Notes 10.5.3; 10.5.7

Stack unwinding releases fully constructed local owners

An exception transfers control to a matching handler and destroys automatic objects on the way.

Copying into a base value discards the derived part
Notes 10.6.2; 10.6.10

Copying into a base value discards the derived part

A pointer or reference can preserve access to the complete object; a base value cannot contain it.

Copying a pointer is not copying its owned storage
Notes 10.4.10; 10.4.18; 10.4.19

Copying a pointer is not copying its owned storage

A raw owning pointer needs an explicit copy policy; this example uses independent deep copies.

A proxy separates reading a cell from writing it
Notes 10.4.25

A proxy separates reading a cell from writing it

The indexing result carries the array and index until its use determines the operation.

One template produces type-specific operations
Notes 10.7.1; 10.7.2; 10.7.3

One template produces type-specific operations

Template arguments are chosen at compile time; ordinary calls then use instantiated code.

A member call passes an object as well as arguments
Notes 10.3.1; 10.3.2

A member call passes an object as well as arguments

Two objects share method code; the implicit object pointer chooses which state the method sees.

A virtual call follows the actual object type
Notes 10.6.5; 10.6.6

A virtual call follows the actual object type

Shape* describes the interface; the referenced object chooses the final override.

A callback adapter restores object-specific behavior
Notes 10.11.2; 10.11.10

A callback adapter restores object-specific behavior

A static bridge matches the toolkit signature, then invokes a virtual operation on the widget object.

11. Functional and logic programming / 12 diagrams

A closure keeps the environment of its creation
Notes 11.1.9; 11.1.10

A closure keeps the environment of its creation

The captured binding belongs to the lexical environment, not to the caller that invokes the closure.

Two lists can share a tail without copying it
Notes 11.1.3; 11.1.6

Two lists can share a tail without copying it

A cons cell contains a head and a tail. Sharing is safe while the shared cells remain unchanged.

A continuation represents the rest of a computation
Notes 11.2.4; 11.2.5

A continuation represents the rest of a computation

At the marked point, the waiting context is “add 1 to the value produced here”.

Currying replaces a tuple input with a returned function
Notes 11.5.14

Currying replaces a tuple input with a returned function

f(x,y) = 10*x + y becomes a function that accepts x, then returns a function awaiting y.

The same list can be program structure or data
Notes 11.1.4; 11.1.7

The same list can be program structure or data

Evaluation interprets a form; quotation returns its structure without evaluating that form.

A fixed point ties a recursive function back to its body
Notes 11.5.15

A fixed point ties a recursive function back to its body

For a list sum, the transformer receives the recursive operation instead of calling itself by name.

A finite demand can use an infinite structure
Notes 11.5.12; 11.5.13

A finite demand can use an infinite structure

Keep the tail suspended; unfold only enough cells to satisfy the consumer.

Lazy evaluation delays work and shares its result
Notes 11.5.1

Lazy evaluation delays work and shares its result

A suspended computation is evaluated only when demanded; later uses can reuse the value.

Map preserves the shape; fold summarizes the sequence
Notes 11.1.11; 11.5.11

Map preserves the shape; fold summarizes the sequence

Both take a function as an argument, but they organize the computation differently.

Backtracking explores alternatives and undoes bindings
Notes 11.4.5; 11.4.6

Backtracking explores alternatives and undoes bindings

Facts are tried in order; failure resumes the most recent remaining choice.

One relation can be queried in several directions
Notes 11.4.7

One relation can be queried in several directions

append(A,B,C) relates a prefix, a suffix and their concatenation.

Unification finds a consistent substitution
Notes 11.4.3; 11.4.4

Unification finds a consistent substitution

Matching proceeds through the structure of both terms; repeated variables must agree everywhere.

12. Tcl and execution strategies / 6 diagrams

Embedding creates a two-way boundary between C and Tcl
Notes 12.3.1; 12.3.2

Embedding creates a two-way boundary between C and Tcl

C owns the interpreter; registered commands let scripts call selected application operations.

Execution strategies differ in which representations run
Notes 12.5.3

Execution strategies differ in which representations run

A language can have several implementations; source syntax alone does not choose the execution strategy.

Self-contained delivery is a boundary around dependencies
Notes 12.5.5; 12.5.7

Self-contained delivery is a boundary around dependencies

Bundling a runtime changes deployment; it does not by itself change interpretation into native compilation.

Braces delay substitution until the receiving command acts
Notes 12.2.3

Braces delay substitution until the receiving command acts

The outer parser preserves a braced word; expr or if can later interpret that word as an expression.

Tcl groups words before ordinary substitution
Notes 12.2.1; 12.2.2; 12.2.3

Tcl groups words before ordinary substitution

A substituted value stays inside its word; spaces in the value do not become extra arguments.

Widget names express containment; a manager controls layout
Notes 12.4.3; 12.4.4

Widget names express containment; a manager controls layout

The same parent-child tree can be arranged geometrically without absolute coordinates in every child.