← C ProgrammingC PROGRAMMING 1.2

Pointers and Memory

The core chapter for driver work. Closed out at a perfect topic final test score.

This is the chapter everything else in driver work actually depends on. Structs, arrays, strings, dynamic memory, MMIO — all of it is pointers wearing a different hat. Eight chapters, going from what an address even is to reading and writing hardware registers through a raw pointer.

The eight chapters

  • A — Pointer Foundations. Memory as boxes with addresses, & to get an address, * to declare and dereference, and the fact that an uninitialized pointer holds garbage — it points somewhere, just not anywhere useful.
  • B — Pointers in Action. Actually reading and writing through a pointer, reassigning it elsewhere, watching the original variable change live, and NULL as "points at nothing, on purpose."
  • C — Pointer Arithmetic & Arrays. Array decay to pointer, why p++ moves by the size of the type and not one byte, indexing as pointer-arithmetic sugar, and the *p++ / *++p / (*p)++ forms that all look almost the same.
  • D — Pointers and Functions. The whole reason pointers exist — passing an address so a function can modify the caller's variable, the classic swap function, and returning pointers safely.
  • E — Multi-Level Pointers. int **pp — a pointer to a pointer — used when a function itself needs to allocate or reassign a pointer that belongs to the caller.
  • F — Dynamic Memory. malloc/free, always checking for NULL, and the three ways to shoot myself in the foot: leaks, use-after-free, double free.
  • G — Pointer Bugs, const, void*, volatile. Wild and dangling pointers, the different const combinations, void* as C's generic pointer, and a first look at volatile.
  • H — Memory Layout & MMIO Patterns. The five memory segments a running program actually occupies, and the pattern that's the whole point of this chapter existing: casting an address to a pointer and reading/writing a hardware register through it.

Where this lands in driver work

Nearly all of it, honestly — this topic basically is driver work. The MMIO pattern in Chapter H is the direct blueprint for register access; double pointers from Chapter E show up in the allocate-and-hand-back-a-struct shape that probe() functions use constantly; and the discipline from Chapter F — NULL checks, no leaks, no double frees — is exactly what the kernel's devm_* allocation APIs exist to enforce automatically.

Notes from readers

Comments — via GitHub