Virtual memory pages and offsets
What you'll learn: How the operating system organizes memory into fixed-size chunks to efficiently map your program's addresses to physical RAM.
The Library Analogy
Imagine a massive library with millions of individual pages. If you asked a librarian for "Page 4,500,201," they would struggle to find it. Instead, libraries use books. To find a specific piece of information, you need two numbers: the Book Number and the Page Number within that book.
Virtual memory works exactly like this. The CPU doesn't see memory as one long continuous string of bytes. Instead, it divides memory into fixed-size blocks called Pages.
Pages and Offsets
In most modern systems, a single page is 4096 bytes (4 KB).
When your C program accesses a memory address, that address is actually composed of two hidden parts:
- The Page Number: Which "book" are we looking in?
- The Offset: Which specific byte ("page") inside that book are we reading?
When you request a variable at a specific virtual address, the hardware (the MMU) looks at the top bits of the address to find the Page Number. It then looks at its "table of contents" (the Page Table) to see where that page sits in the physical RAM chips. The "Offset" stays the same—it’s just the distance from the start of that page.
Seeing the Math
We can simulate how the CPU splits an address using the bitwise operators we learned earlier. Since , the last 12 bits of any address represent the offset.
#include <stdio.h>
#include <stdint.h>
int main() {
int secret_data = 42;
uintptr_t addr = (uintptr_t)&secret_data;
// A standard page is 4096 bytes (0x1000 in hex)
// The offset is the remainder when dividing by page size
uintptr_t page_number = addr / 4096;
uintptr_t offset = addr % 4096;
printf("Virtual Address: %p\n", (void*)addr);
printf("Operating on Page: %lu\n", page_number);
printf("Byte offset within page: %lu\n", offset);
return 0;
}
Why this matters
By breaking memory into pages, the OS doesn't have to find one giant continuous block of RAM for your program. It can scatter "Page 1" in one corner of the RAM and "Page 2" in another. As long as the OS keeps track of the mapping, your program feels like it has one smooth, continuous space to work in.
Key takeaway
Virtual memory is divided into fixed-size pages (usually 4KB), and every address identifies a specific page number and a byte offset within that page.