AlgoPlusAlgoPlus
Learn/Operating Systems
Lesson

Paging

Scatter a program's memory across fixed-size frames and translate every address through a page table — O(1) lookup, no external fragmentation.

8 min read Watch it move Build it

Paging lets a program's memory be scattered all over physical RAM instead of sitting in one continuous block — and lets parts of it stay on disk until they're actually touched. The OS cuts a program's address space into fixed-size pages and cuts RAM into equal-size frames. A page can go in *any* free frame; a page table records which frame each page landed in.

The mental model
Think of pages and frames as same-sized boxes. Any page fits in any frame, so the OS never has to hunt for a big-enough contiguous gap — it just grabs any free frame. The page table is the index that remembers where each box went.

A virtual address is two numbers

Programs use virtual addresses that say nothing about where data physically sits. The hardware splits each one into a page number and an offset into that page. If the page size is a power of two, this split is just slicing the bits: the low bits are the offset, the high bits are the page number. Translation keeps the offset and swaps the page number for its frame.

// Page size = 1024 bytes (2^10), so the low 10 bits are the offset.
// Page table: pageTable[pageNumber] = frameNumber
const pageSize = 1024;

function translate(virtualAddr, pageTable) {
  const page   = Math.floor(virtualAddr / pageSize);
  const offset = virtualAddr % pageSize;
  const frame  = pageTable[page];          // which frame holds this page
  return frame * pageSize + offset;        // physical address
}

Worked example

  1. 1Page size is 1024 bytes, and the program reads virtual address 1500.
  2. 2Page number = 1500 / 1024 = 1; offset = 1500 % 1024 = 476.
  3. 3The page table says page 1 currently lives in frame 4.
  4. 4Physical address = 4 * 1024 + 476 = 4572 — same offset, new frame.
  5. 5If page 1 were marked *not loaded*, this access would trigger a page fault and the OS would fetch it from disk first.
Internal fragmentation, not external
Paging kills *external* fragmentation — any free frame works. But the last page of a process is rarely exactly full, wasting part of one frame. That leftover inside an allocated frame is internal fragmentation, averaging about half a page per process.
The TLB keeps it fast
A naive lookup needs an extra memory access just to read the page table. The TLB (Translation Lookaside Buffer) caches recent page-to-frame mappings, so the common case translates in hardware with no extra trip to RAM.
OperationTimeSpace
Address translation · page table entry per page; TLB caches hot onesO(1)O(pages)
Check yourself
Page size is 1024 bytes and page 1 maps to frame 4. What physical address does virtual address 1500 translate to?