Logical vs Physical Address Space
Learn how CPUs and operating systems translate virtual addresses, use segmentation, and map process memory to physical memory.
Learn how CPUs and operating systems translate virtual addresses, use segmentation, and map process memory to physical memory.
Logical vs Physical Address Space
In a process running with virtual memory, a pointer such as the illustrative address 0x00007fff12345000 is a virtual address. The CPU and operating system translate it through the memory-management hardware before accessing a physical location. Different processes can use the same virtual address while mapping it to different physical pages; several virtual mappings can also share one physical page.
This distinction explains how a process can use a private address space while the OS maps memory onto shared hardware.
When to Use / When Not to Use
On systems that use virtual memory, understanding the difference between a process address and a physical address matters most when:
When you benefit from knowing it:
- Debugging segmentation faults (was the fault caused by an invalid logical address or a protection violation?)
- Writing low-level systems code that interacts with the kernel (mmap, mprotect, shmget)
- Optimizing for TLB behavior (understanding which logical pages map to which physical frames)
- Understanding ASLR (Address Space Layout Randomization) and why it mitigates exploits
When you do not need to think about it:
- Writing application code in high-level languages (Python, JavaScript, Go)
- Web services and API handlers
- Standard CRUD operations where the runtime handles memory
In ordinary application code, a pointer refers to a virtual address in the process’s address space. Kernel code, device drivers, and bare-metal systems may work with other address spaces or translation rules. The details depend on the CPU architecture and operating system.
Architecture or Flow Diagram
This simplified path shows what happens on a system with paged virtual memory. A TLB miss starts a page-table walk; it is not itself a page fault.
flowchart TD
VA["CPU requests a virtual address"] --> TLB{"Translation in TLB?"}
TLB -->|"Hit"| PA["Check access and form physical address"]
TLB -->|"Miss"| WALK["Walk page tables<br/>using this architecture's rules"]
WALK -->|"Mapping exists and access allowed"| CACHE["Cache translation in TLB"]
CACHE --> PA
WALK -->|"No usable mapping or access denied"| FAULT["Page-fault exception"]
FAULT --> HANDLER["OS handles the fault"]
HANDLER -->|"Resolved: map, copy, or load page"| RETRY["Retry instruction"]
RETRY --> VA
HANDLER -->|"Cannot resolve"| ERROR["Deliver process error or signal"]
PA --> MEM["Access physical memory or device"]
The TLB caches recent translations. If an entry is absent, the processor or operating system follows the architecture’s page-table rules. A valid mapping can be found and cached without a page fault. A page fault is an exception raised when the requested mapping or access cannot be completed directly. The OS may handle it through lazy allocation, copy-on-write, or by bringing in file-backed or swapped data. It sends a signal such as SIGSEGV when the address is unmapped or the access violates protection. Fault handling does not always involve disk I/O.
Core Concepts
Logical (Virtual) Address Space
The CPU issues virtual addresses for the active address space. The available range depends on the architecture, processor mode, operating-system configuration, and process layout; a 64-bit pointer does not mean every bit pattern is a usable address. As one example, some Linux/x86-64 configurations use 48-bit virtual addresses, while other supported configurations can differ. Check the platform documentation before relying on a particular range.
The OS gives each process its own mappings. Two processes can use the same virtual address and map it to different physical frames, or intentionally map the same frame for shared memory. Ordinary user-space code has no generic Linux read_cr3() API for reading the active page-table root; access to architecture registers is privileged and platform-specific.
Physical Address Space
Physical addresses identify locations on the system’s physical address map. That map can include DRAM, device memory such as memory-mapped I/O (MMIO), and address gaps; it is not simply the amount of RAM installed. The addressable range depends on the processor and platform. A process normally sees virtual addresses, not raw physical addresses.
As an illustrative example, two neighboring virtual pages might map to non-neighboring physical frames. The addresses and frame numbers in a real system depend on its mappings; the OS manages them and the CPU enforces the access rules.
Segmentation (Historical and Modern)
Segmentation is one memory-protection and address-translation design, but it is not a universal model for current CPUs. In classic segmentation, an address combines a segment selector and an offset; the architecture uses a descriptor to apply a base and limit. That model is useful for understanding historical x86 modes, but it should not be applied to every architecture.
For example, x86-64 operating systems generally use a flat address space with paging for ordinary process memory. The architecture still defines segment registers, and operating systems may use bases such as FS or GS for thread-specific data. Other CPUs and operating systems expose different mechanisms.
The MMU and Address Translation
The MMU performs or coordinates address translation. A TLB stores recent virtual-to-physical mappings; when a translation is missing, the architecture’s page-table mechanism supplies it. Page-table depth, entry format, page size, and the division of work between hardware and the OS differ by architecture and configuration.
Linux’s memory-management code presents a five-level software page-table hierarchy and folds unused levels to fit the hardware. This is an architecture-neutral kernel interface, not a claim that every CPU has five hardware levels. For a concrete example, x86-64 page walks use architecture-defined levels and registers; other systems use their own structures. The page offset is preserved within a mapped page, while the frame and permissions come from the mapping. See the Linux page-table documentation.
Production Failure Scenarios + Mitigations
Page Table Bloat in Large Mappings
Failure: Applications that map and touch large files can use substantial page-table memory. As an illustration, on x86-64 Linux with 4 KiB base pages, 8-byte entries, and a fully populated 100 GB mapping, the leaf page-table entries alone take about 200 MB; upper-level tables add overhead. Sparse mappings and larger pages change that estimate.
Mitigation: Where supported, larger pages can reduce page-table overhead for large mappings. For example, x86 systems may support 2 MiB or 1 GiB pages; Linux offers transparent and explicit huge-page options. The tradeoff is increased internal fragmentation for sparse or small allocations. Check the target platform and workload before enabling them.
TLB Shootdowns Under Heavy Context Switching
Failure: Address-space changes can make cached TLB entries stale. The required invalidation depends on the architecture, OS, and hardware features. Some systems tag translations with an address-space identifier and can retain entries across context switches; mapping changes may still require targeted invalidations or cross-core shootdowns. The cost depends on the workload and platform, so measure it rather than assuming a fixed overhead.
Mitigation: Use the address-space tagging and invalidation features supported by the target OS and CPU. Linux can use ASIDs on supported architectures; x86 has PCIDs. These features can avoid some broad flushes, but they do not eliminate all invalidation work. Profile the target workload and consult the relevant architecture documentation.
Address Space Layout Randomization Collisions
Failure: ASLR randomizes where the stack, heap, libraries, and mapped regions load in the virtual address space. The available entropy depends on the architecture, OS configuration, and alignment. Address leaks can still expose useful locations, so ASLR does not replace other exploit mitigations.
Mitigation: Build executables as position-independent where the platform supports it, and combine ASLR with other platform protections. On Linux, /proc/sys/kernel/randomize_va_space reports the configured ASLR policy; it does not measure the entropy of every mapping.
Trade-off Table
This table compares classic memory-management models. Current systems combine mechanisms according to their CPU and OS; it is not a universal description of every architecture.
| Aspect | Pure Segmentation | Pure Paging | Hybrid Segmentation + Paging |
|---|---|---|---|
| External fragmentation | High (segments must be contiguous in physical memory) | None for fixed-size paging | Depends on the combination |
| Internal fragmentation | None | Possible; an illustrative 4 KiB page may leave unused space | Depends on page and segment sizes |
| Memory protection granularity | Segment-level (coarse) | Page-level (an illustrative 4 KiB base page is fine-grained) | Segment + page |
| Page table overhead | None (segment descriptors are small) | Multi-level page tables for large address spaces | Reduced (segment base + page offset) |
| TLB efficiency | Depends on segment ranges and implementation | Depends on page size and working set | Depends on architecture and mapping |
| Complexity | Simple hardware | Moderate (page table walks) | High |
| How to read this model | Abstract model; current systems vary | Abstract model; systems often combine paging with other mechanisms | Abstract model; use depends on architecture and OS |
Implementation Snippets
Examining Your Virtual Address Space (C)
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
/* Read and print the maps file that shows this process's
* virtual address space layout. Each line describes a mapped
* region: start-end perms offset device inode pathname */
void print_virtual_mappings(void) {
FILE *maps = fopen("/proc/self/maps", "r");
if (!maps) {
perror("fopen /proc/self/maps");
return;
}
char line[512];
printf("%-18s %-10s %-6s %s\n",
"Address range", "Permissions", "Offset", "Pathname");
printf("%-18s %-10s %-6s %s\n",
"-------------", "------------", "------", "--------");
while (fgets(line, sizeof(line), maps)) {
// Example line:
// 00400000-0040c000 r-xp 00000000 fd:00 123456 /bin/bash
printf("%s", line);
}
fclose(maps);
}
/* Linux example: show this process's virtual mappings and RAM total. */
int main(void) {
printf("Process ID: %d\n", getpid());
printf("Virtual mappings for this Linux process:\n");
printf("Linux MemTotal (usable RAM): ");
FILE *meminfo = fopen("/proc/meminfo", "r");
char line[256];
while (fgets(line, sizeof(line), meminfo)) {
if (strncmp(line, "MemTotal:", 9) == 0) {
printf("%s", line);
break;
}
}
fclose(meminfo);
print_virtual_mappings();
return 0;
}
Inspecting Linux virtual mappings
PID=1234
cat "/proc/$PID/maps"
On Linux, /proc/PID/maps lists virtual mappings and their permissions. /proc/PID/pagemap is a binary interface with per-page metadata; it is not a text command that translates an address when read with cat. The kernel masks physical frame numbers from callers without CAP_SYS_ADMIN, so ordinary application code cannot rely on it to inspect physical addresses. See the Linux pagemap documentation.
Observability Checklist
- TLB hit/miss rates: Where supported by the CPU and
perf, tryperf stat -e dTLB-loads,dTLB-load-misses,dTLB-stores,dTLB-store-misses ./program; checkperf listfor available events. - Page fault frequency and type: On Linux,
ps -o majflt,minfltreports major and minor fault counts; the meanings are OS-specific. - Page-table walker events: Event names are CPU-specific; check
perf listand the processor documentation before collecting them. - Virtual memory map size:
ps -o vsz,rss(virtual size vs resident set size) — large gap indicates memory-mapped files or swapped regions - Linux ASLR policy:
cat /proc/sys/kernel/randomize_va_spacereports the configured policy; it does not measure entropy. - Large page usage:
cat /proc/meminfo | grep -i huge— shows transparent huge page and explicit huge page statistics - OOM (Out of Memory) killer:
dmesg | grep -i "out of memory"orjournalctl -k | grep -i oom— shows when the OOM killer invoked - swapped pages:
vmstat 1—siandsocolumns show swap-in and swap-out rates
Security/Compliance Notes
Address Space Layout Randomization (ASLR): Depending on the OS and configuration, ASLR can vary locations such as the stack, heap, libraries, and mapped regions when a process starts. Linux also maps a VDSO. Randomization makes fixed-address assumptions less reliable, but information leaks can still reveal addresses.
Kernel Address Space Layout Randomization (KASLR): Linux can randomize the kernel image’s load location at boot when the architecture and configuration support it. This makes hardcoded kernel addresses less reliable, but information leaks can reveal the layout. The available randomization depends on the platform and configuration.
SMEP (Supervisor Mode Execution Prevention) and SMAP (Supervisor Mode Access Prevention): On supported x86 CPUs and operating systems that enable them, these features restrict supervisor-mode execution of user pages (SMEP) and access to user pages (SMAP). Their availability and behavior depend on the architecture and configuration.
Meltdown/Spectre Impact on Address Translation: Mitigations for speculative-execution vulnerabilities depend on the CPU and OS. Some configurations use measures such as Kernel Page Table Isolation, which can add overhead to user/kernel transitions. The performance effect varies; it should not be treated as a fixed cost on every system call or page-table walk.
Common Pitfalls / Anti-patterns
Pitfall: Assuming virtual address spaces are not fragmented.
The virtual address space can become fragmented through repeated mmap/munmap cycles, leaving gaps between mapped regions. A large contiguous virtual mapping can fail with ENOMEM if no single free virtual-address range is large enough, even when the total free virtual space is larger.
Pitfall: Writing to memory-mapped files without understanding write-back behavior.
mmap with MAP_SHARED updates the file through the OS page cache; changes may not reach persistent storage immediately. For durability-critical data, use msync() as appropriate. MAP_POPULATE is an mmap flag that requests prefaulting; it does not make writes durable.
Pitfall: Confusing virtual memory with swap space. Virtual memory is the address-space and mapping system provided by the OS. Swap is one possible backing store for some pages. A system can use virtual memory without swap; exhausting swap does not by itself mean the OOM killer will run. Virtual address-space exhaustion and memory pressure are different problems.
Anti-pattern: Pointer arithmetic assuming 32-bit addressing on a 64-bit system.
On a 64-bit system, sizeof(void*) is 8 bytes. If you store a pointer in a 32-bit integer (uint32_t), you truncate the upper bits, silently corrupting the address. GCC’s -Wpointer-to-int-cast and -Wint-to-pointer-cast flags catch these. UBSan (Undefined Behavior Sanitizer) also detects them.
Quick Recap Checklist
- In an ordinary virtual-memory process, pointers name virtual addresses; physical addresses belong to the system’s physical map
- A TLB hit uses a cached mapping; a miss may be resolved by a page-table walk, while an unresolved mapping or access can raise a page fault
- Page-table structure depends on the CPU and OS; Linux’s software hierarchy can fold levels not used by the hardware
- Segmentation and paging details vary by architecture; x86-64 Linux is one example, not a model for every system
- ASLR can vary virtual mapping locations to make hardcoded addresses less reliable
- TLB invalidation behavior and cost depend on architecture, OS, and hardware tagging support
- Page tables also use memory; larger pages can reduce the number of entries for some workloads
- Virtual-address-space exhaustion is different from physical-memory pressure, which can trigger OS-specific reclaim or OOM policy
- Linux tools such as
/proc/PID/maps, pagemap metadata, andperfTLB events can help inspect mappings; PFN access is restricted and hardware counters vary by CPU. - Where supported and enabled, SMEP/SMAP restrict supervisor access to user-space memory
Interview Questions
A page fault is an exception raised when the current translation or access cannot complete. The OS may resolve it by allocating a page lazily, handling copy-on-write, or mapping data that is already in memory or must be read from storage. It then updates the mapping and resumes the instruction. If the address is unmapped or the access violates protection, Linux may deliver a signal such as SIGSEGV. A page fault is not the same thing as that signal; fault details such as saved-address registers are architecture-specific.
The Translation Lookaside Buffer caches recent address translations. A hit uses the cached mapping. On a miss, the architecture may walk page tables in hardware or involve OS-specific handling. If the walk finds a valid mapping with permitted access, the translation can be cached and execution continues; a miss alone is not a page fault. The cost of either path depends on the CPU, caches, page-table format, and workload, so there is no portable cycle count.
ASLR varies mapping locations so an exploit cannot assume a fixed address. The available entropy depends on the platform and configuration. It does not help if an attacker can learn the addresses at runtime, and it is not a substitute for protections such as non-executable memory or control-flow defenses.
On Linux, a minor page fault is handled without storage I/O. It can result from lazy allocation, copy-on-write, or finding file-backed data already in the page cache. A major page fault requires storage I/O to bring data in. The minflt and majflt process counters report these categories; their exact accounting is OS-specific. A fault is not automatically a disk read.
On Linux, fork() gives the child a separate virtual address space that initially shares many of the parent's pages through copy-on-write. A write to a shared page can make the kernel allocate and copy a page, then update the mappings. The exact implementation is an OS detail; programs should rely on the process semantics documented by their platform, not on a fixed physical-memory cost.
These are classic models, and current CPUs and OSes implement address translation differently. In segmentation, an address is interpreted through a segment descriptor with a base and limit. In paging, virtual pages map to physical frames; page sizes vary by platform. For example, x86-64 Linux uses paging for ordinary process memory and retains limited segment-register uses such as thread-local storage. That example does not describe every architecture or OS.
The TLB caches translations. On a miss, a page-table walk follows the levels defined by the architecture and OS. If it finds a valid mapping and the requested access is allowed, the translation can be cached and the instruction continues. If the mapping is absent or access is denied, the processor raises a page fault for the OS to handle. A TLB miss by itself does not mean a page fault; the number of levels and the walk cost vary by system.
These are different Linux interfaces. vmalloc is a kernel allocator that returns virtually contiguous memory backed by physical pages that need not be contiguous; its available range depends on the architecture and kernel configuration. mmap(MAP_ANONYMOUS) creates a mapping in a process's virtual address space. It is not necessarily the process heap, and its pages may be allocated lazily. Neither interface by itself promises a physically contiguous or device-ready DMA buffer; Linux drivers should use the DMA API for that. User applications use mmap for large mappings when it fits their needs.
A page-table entry records a mapping and access attributes. On x86-64, entries can include present, read/write, user/supervisor, accessed, and dirty information, along with a page-frame number. The exact bit layout depends on the architecture and paging mode; the offset within the page comes from the original virtual address.
A page fault is a processor exception raised when a translation is missing or the requested access cannot proceed. The OS may resolve it, for example by allocating a page, applying copy-on-write, or loading backing data. If the address is unmapped or the access violates protection, Linux may report the failure with a signal such as SIGSEGV (some cases use SIGBUS). A fault is therefore not automatically an error signal, and the names and handling differ by platform.
Virtual-memory address ranges depend on the CPU and OS; they are not a fixed size on all 64-bit systems. Swap is one possible backing store for evicted anonymous pages. File-backed mappings may instead be read again from their file, and systems without swap can still use virtual memory. When a page must be brought back, the OS handles a page fault and updates the mapping. The representation of swap entries in page tables is architecture- and OS-specific.
Linux KASLR randomizes the kernel image's location at boot on supported architectures and configurations. Its effective range depends on the platform and boot configuration, so there is no universal base address or entropy figure. A hardcoded address from one x86-64 kernel build is only an illustration, not a general kernel address. KASLR can also be weakened by information leaks and works alongside other mitigations whose availability and behavior vary by CPU and kernel.
A TLB shootdown invalidates translations that other CPUs may have cached after a mapping changes. Context switches and address-space identifiers affect which translations can be retained, but a context switch does not always flush every TLB entry. CPUs and operating systems may use identifiers such as x86 PCIDs or ASIDs on other architectures. The exact invalidation operations and cost depend on the system; measure the target workload rather than assuming a fixed penalty.
Kernel memory allocators vary by OS. In Linux, common interfaces include kmalloc for smaller kernel allocations and vmalloc for virtually contiguous ranges whose backing pages need not be physically contiguous. Slab allocators reuse objects of common sizes; the buddy allocator manages page-sized blocks. These mechanisms reduce some forms of fragmentation, but no allocator eliminates all fragmentation or applies uniformly across kernels.
On Linux, kmalloc is used for kernel allocations that need a virtually contiguous range; the allocator's physical-contiguity guarantees and practical size limits depend on the allocation and platform. vmalloc returns a virtually contiguous range backed by pages that need not be physically contiguous. Its address range and allocation constraints vary by architecture and configuration. These are kernel interfaces, not general user-space allocation APIs. Drivers should use the Linux DMA API when they need device-accessible memory rather than assuming either allocator supplies a suitable DMA buffer.
Larger pages can reduce the number of translations needed for a fixed mapping size. As an x86 example, a 16 GiB mapping uses fewer 2 MiB pages than 4 KiB base pages, where both sizes are supported. Whether that helps depends on the CPU's TLBs, the operating system, allocation policy, and workload. Large pages can also waste more memory for small or sparse mappings. Explicit and transparent huge pages have different allocation and reclaim behavior. Measure the target workload; there is no general throughput gain that applies to every database server.
On x86, page-table permissions can restrict user-mode access to supervisor-only mappings. The OS handles a disallowed access according to its fault and signal rules. Kernel Page Table Isolation (KPTI) is an x86 mitigation that changes which mappings are present during user and kernel execution; whether it is enabled depends on the CPU, kernel, and configuration. Other architectures use different privilege and translation mechanisms.
If active memory demand stays above available RAM, an OS may reclaim pages, write data to swap, or evict clean file-backed pages. Some faults require storage I/O; others, such as copy-on-write or lazy allocation, do not. Under sustained pressure, applications can spend much of their time waiting for memory to be reclaimed or read back. The page-replacement policy and tuning options vary by OS. Diagnose with the platform's memory and fault counters before changing memory limits or page-size settings.
On Linux, /proc/sys/kernel/randomize_va_space reports the configured ASLR policy: 0 disables it, 1 randomizes mmap-related locations and the stack, and 2 also randomizes the heap. To inspect a process, read /proc/PID/maps while it is running; /proc/self/maps refers to the process opening that file. Repeated runs of a PIE-enabled program can show whether its mappings vary, though the amount of randomization depends on architecture and configuration.
Devices may occupy ranges in the physical address map. On Linux, kernel drivers map device registers with APIs such as ioremap; a driver can also expose a controlled device mapping to a userspace process when its interface permits it. Cacheability and ordering requirements depend on the device and architecture, so drivers must use the platform's MMIO access rules. This is different from giving an application unrestricted access to arbitrary physical addresses.
Further Reading
- Paging & Page Tables — the data structures that map virtual pages to physical frames at the hardware level
- Virtual Memory — how the OS extends physical memory using disk as a backing store via demand paging
- What Every Programmer Should Know About Memory — Ulrich Drepper — foundational paper on DRAM, cache, and TLB behavior from Red Hat
- Understanding the Linux Kernel — Bovet & Cesati — Chapter 8 covers virtual memory, page tables, and address translation in detail
Conclusion
On systems with paged virtual memory, the CPU and OS use address translation to isolate processes and map their virtual pages onto physical memory or devices. The details vary by architecture and configuration.
Some Linux/x86-64 configurations expose a 48-bit virtual-address range, but that value is not universal. Page-table levels, supported page sizes, and physical-address visibility vary across systems. Copy-on-write and demand paging are examples of OS techniques that change mappings as a process runs.
To inspect one Linux process’s virtual mappings, start with /proc/PID/maps. The paging and page tables guide explains the mapping structures; the virtual memory guide covers how operating systems manage resident and backed pages.
Category
Related Posts
ASLR & Stack Protection
Explore ASLR, PIE, stack canaries, and NX on Linux with GCC, then inspect a harmless C program to see what each mitigation does and where it falls short.
Assembly Language Basics: Writing Code the CPU Understands
Learn x86-64 Linux assembly with the System V ABI: track registers, assemble and run a small program, debug it in GDB, then compare AArch64.
Boolean Logic & Gates
Understanding AND, OR, NOT gates and how they combine into arithmetic logic units — the building blocks of every processor.