Memory Management & Paging
Logical vs physical addresses, the MMU, contiguous allocation and fragmentation, paging with worked address translation, page-table structures (multi-level, hashed, inverted), the TLB and effective access time, segmentation, and kernel allocators.
Goals of memory management
- Isolation — a process can't read or corrupt another's memory (or the kernel's).
- Relocation — programs don't need to know where in RAM they'll be loaded.
- Efficient sharing — shared libraries and copy-on-write pages exist once in RAM.
- Abstraction — each process sees a large, contiguous address space.
- Efficient use — little waste, fast allocation, support for more virtual memory than RAM (next chapter).
Logical vs physical addresses
The CPU issues virtual addresses; the MMU translates each one to a physical address on the fly. In the simplest scheme, a relocation (base) register is added and a limit register checked:
physical = base + logical if logical < limit
trap (segmentation fault) otherwise
Address binding can happen at compile time (absolute code), load time (relocatable code), or — in every modern OS — execution time, via the MMU.
Contiguous allocation and fragmentation
Early systems gave each process one contiguous region. Free memory becomes a list of holes, and choosing a hole needs a policy:
| Policy | Rule | Notes |
|---|---|---|
| First fit | first hole big enough | fast, usually good |
| Next fit | first fit, starting where the last search ended | spreads allocations |
| Best fit | smallest hole big enough | leaves tiny useless holes; must search all |
| Worst fit | largest hole | leaves big holes; generally worst in practice |
External fragmentation: free memory is scattered in small holes. The 50-percent rule: with first fit, for N allocated blocks about 0.5N blocks are lost to fragmentation. Compaction helps but requires relocatable processes and is slow. The real fix is paging.
Paging
Divide virtual memory into pages and physical memory into frames of the same fixed size (4 KB typical; 2 MB and 1 GB "huge pages" available). Any page can go in any frame, so there's no external fragmentation.
Worked example
32-bit virtual addresses, 4 KB (2¹²) pages:
- Offset = 12 bits, page number (VPN) = 20 bits → 2²⁰ ≈ 1 M pages.
- Address
0x00403A7C→ VPN =0x00403, offset =0xA7C. - Page table entry 0x403 says frame
0x1F2, valid, read/write. - Physical address =
0x1F2× 0x1000 +0xA7C=0x1F2A7C.
Quick formulas:
| Quantity | Formula |
|---|---|
| offset bits | log₂(page size) |
| number of pages | 2^(virtual bits − offset bits) |
| number of frames | physical memory / page size |
| page table size (single-level) | #pages × PTE size |
Example: 32-bit VA, 4 KB pages, 4-byte PTEs → 2²⁰ × 4 B = 4 MB per process for a flat page table. That's the motivation for hierarchical tables.
Page table entry (PTE) bits
| Bit | Purpose |
|---|---|
| Present/valid | page is in RAM; otherwise access → page fault |
| Read/Write, Execute (NX) | protection; NX blocks code injection |
| User/Supervisor | user mode can't touch kernel pages |
| Accessed (referenced) | set by hardware on access → used by page replacement |
| Dirty | set on write → page must be written back before eviction |
| Cache-disable / write-through | memory-mapped device registers |
Page table structures
Hierarchical (multi-level)
Page the page table itself. 32-bit x86: 10 bits directory + 10 bits table + 12 bits offset. x86-64: four levels of 9 bits each + 12-bit offset = 48-bit virtual addresses (256 TB); five-level paging extends to 57 bits.
Hashed page tables
Hash the VPN into a table of chains (common for address spaces > 32 bits on some architectures). Variant: clustered page tables where each entry maps several consecutive pages.
Inverted page table
One entry per physical frame (not per virtual page), storing (process ID, VPN). Memory use scales with RAM, not address space size; lookups need a hash. Used historically by PowerPC/IA-64. Sharing pages is awkward.
The TLB
Every memory access needs a translation, and a 4-level walk costs 4 extra memory reads. The Translation Lookaside Buffer caches recent translations.
Effective access time (EAT) — with TLB hit ratio h, memory access time m, and a page walk of k reads:
EAT = h·m + (1 − h)·(k + 1)·m (ignoring the TLB lookup time itself)
Example: m = 100 ns, h = 0.98, single-level table (k = 1): EAT = 0.98·100 + 0.02·200 = 102 ns. With a 4-level table (k = 4): 0.98·100 + 0.02·500 = 108 ns.
Ways to improve TLB behaviour:
- Huge pages (2 MB, 1 GB): one entry covers much more memory (TLB reach = entries × page size). Databases and JVMs often enable them.
- ASID/PCID tags avoid flushing the TLB on context switches.
- Locality in your code: sequential access beats random access.
Segmentation
Instead of fixed pages, divide the address space into segments that match the program's logical structure (code, data, heap, stack, each library). A logical address is ⟨segment number, offset⟩; the segment table holds base and limit:
if offset >= limit[s]: trap
physical = base[s] + offset
| Paging | Segmentation | |
|---|---|---|
| Unit size | fixed | variable |
| Visible to programmer | no | yes (logical units) |
| External fragmentation | no | yes |
| Internal fragmentation | yes (last page) | no |
| Protection/sharing granularity | per page | per logical segment |
| Modern use | everywhere | mostly vestigial (x86-64 FS/GS for TLS) |
Allocators inside the system
| Level | Allocator | Idea |
|---|---|---|
| Kernel pages | buddy system | power-of-two blocks, split and coalesce with the "buddy" |
| Kernel objects | slab / SLUB | caches of same-size objects, O(1), cache-warm |
| User heap | malloc (ptmalloc, jemalloc, tcmalloc, mimalloc) | size classes, per-thread caches; brk/mmap for more memory |
| Language runtimes | GC heaps (JVM, Go, .NET) | bump-pointer allocation in thread-local buffers, generational collection |
Memory in practice: what you see in top
- VIRT / VSZ — total virtual address space reserved (can be huge, mostly unbacked).
- RES / RSS — resident set: pages actually in RAM now.
- SHR — portion of RES that's shared (libraries, shared memory).
- Overcommit: Linux lets processes reserve more than RAM+swap; physical pages are allocated on first touch. If RAM runs out, the OOM killer picks a victim (highest
oom_score). In containers, exceeding the cgroup memory limit gets you OOM-killed (exit code 137).
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.