{}DSA Atlas

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.

Intermediate8 interview questions

Goals of memory management

  1. Isolation — a process can't read or corrupt another's memory (or the kernel's).
  2. Relocation — programs don't need to know where in RAM they'll be loaded.
  3. Efficient sharing — shared libraries and copy-on-write pages exist once in RAM.
  4. Abstraction — each process sees a large, contiguous address space.
  5. 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:

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

PolicyRuleNotes
First fitfirst hole big enoughfast, usually good
Next fitfirst fit, starting where the last search endedspreads allocations
Best fitsmallest hole big enoughleaves tiny useless holes; must search all
Worst fitlargest holeleaves 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.

Virtual address VPN 0x00403 0xA7C 20 bitsoffset: 12 bits Page table 0x401 → 0x07C 0x402 → invalid 0x403 → 0x1F2 0x404 → 0x0A9 PTE bits: valid, R/W/X, user/kernel, dirty, accessed Physical address 0x1F2 0xA7C offset copied unchanged = 0x1F2A7C
Translation: page number indexes the page table; the offset passes through unchanged.

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:

QuantityFormula
offset bitslog₂(page size)
number of pages2^(virtual bits − offset bits)
number of framesphysical 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

BitPurpose
Present/validpage is in RAM; otherwise access → page fault
Read/Write, Execute (NX)protection; NX blocks code injection
User/Supervisoruser mode can't touch kernel pages
Accessed (referenced)set by hardware on access → used by page replacement
Dirtyset on write → page must be written back before eviction
Cache-disable / write-throughmemory-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.

PML4 (9) PDPT (9) PD (9) PT (9) offset (12) = 48-bit VA CR3 → L4 L3 table L2 table L1 table frame 4 memory reads on a TLB miss
Only the inner tables actually used are allocated, so sparse address spaces stay cheap.

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:

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

Text
if offset >= limit[s]: trap
physical = base[s] + offset
PagingSegmentation
Unit sizefixedvariable
Visible to programmernoyes (logical units)
External fragmentationnoyes
Internal fragmentationyes (last page)no
Protection/sharing granularityper pageper logical segment
Modern useeverywheremostly vestigial (x86-64 FS/GS for TLS)

Allocators inside the system

LevelAllocatorIdea
Kernel pagesbuddy systempower-of-two blocks, split and coalesce with the "buddy"
Kernel objectsslab / SLUBcaches of same-size objects, O(1), cache-warm
User heapmalloc (ptmalloc, jemalloc, tcmalloc, mimalloc)size classes, per-thread caches; brk/mmap for more memory
Language runtimesGC 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

0 / 8 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.