Memory management

On this page 7

Memory management is the operating system function that allocates physical memory, decides which parts of it each process and the kernel may use, maps the addresses programs see onto real RAM, protects processes from one another and reclaims memory when it is no longer needed. Among OS fundamentals, it sits next to process scheduling and device handling as one of the core duties of the kernel, and it determines how many programs can run at once, how fast they run and how stable the system remains under load.

Modern operating systems implement memory management through virtual memory: every process receives its own private address space, and the kernel, assisted by the processor’s memory management unit, translates those addresses into physical locations page by page.

What memory management has to achieve

Memory management pursues several goals at the same time, and many of its design choices are trade-offs between them. The kernel must keep processes isolated while still allowing controlled sharing, and it must use scarce RAM efficiently without slowing programs down.

GoalWhat it meansTypical mechanism
AllocationGive memory to processes on requestPage allocators, heap and stack growth
ProtectionPrevent illegal access to other memoryPer-process page tables, permission bits
Address translationMap virtual addresses to physical framesMemory management unit and TLB
SharingLet processes use the same physical pagesShared libraries, shared memory, copy-on-write
ReclamationRecover memory that is unused or idleFreeing, page reclaim, swapping, compression
Goals of memory management

Protection also separates user space from kernel space. Kernel pages are marked as privileged, so an ordinary program that tries to read or write them triggers a fault instead of corrupting the operating system.

How virtual addresses become physical memory

Address translation works by splitting memory into fixed-size pages, most commonly 4 KiB, with optional large pages of 2 MiB or 1 GiB on x86-64 and 16 KiB pages on some ARM-based systems. Each process has a page table that records which physical frame, if any, holds each of its virtual pages and which permissions apply.

Walking the page table for every access would be far too slow, so the processor caches recent translations in the translation lookaside buffer, or TLB. A TLB hit costs almost nothing, while a miss requires a table walk of several memory reads. This is one reason large pages help memory-hungry databases and virtual machines.

When a program touches a page that is not currently mapped, the processor raises a page fault and the kernel decides what to do. The table below shows the common outcomes.

Fault typeCauseKernel responseRelative cost
Minor faultPage is in RAM but not yet mappedUpdate the page tableMicroseconds
Major faultPage must be read from disk or swapLoad the page, then map itUp to milliseconds
Copy-on-write faultWrite to a shared, read-only pageCopy the page for the writerMicroseconds
Invalid accessAddress not allowed for the processSignal or terminate the processEnds the operation
Kinds of page faults and their cost

Allocation inside the kernel and inside processes

Memory is allocated at two distinct levels. The kernel hands out whole physical pages, while the runtime library inside each process divides those pages into the small objects that programs request with calls such as malloc or the new operator.

  • Page allocators such as the buddy system manage physical frames in power-of-two blocks to limit fragmentation.
  • Slab or object caches keep pools of frequently used kernel structures ready for reuse.
  • User-space heap allocators request large regions from the kernel through system calls and subdivide them.
  • Garbage collectors in managed languages reclaim unreachable objects automatically, on top of the OS allocator.

Operating systems usually practice lazy allocation: a request reserves address space, but physical pages are assigned only when they are first touched. This makes process creation and large reservations cheap, but it also enables overcommitment, in which the promised memory exceeds what physically exists.

Behavior under memory pressure

When free RAM runs low, memory management must reclaim pages from somewhere. The kernel first drops clean file cache pages, which can be reread from disk, then compresses or writes out anonymous pages to swap or the page file, and as a last resort it terminates processes.

StrategyHow it frees memoryMain drawback
Dropping file cacheDiscards clean cached file dataLater reads hit the disk again
Memory compressionStores idle pages in compressed RAMUses CPU time for compression
Paging to diskWrites idle pages to swap or page fileMajor faults when pages return
Out-of-memory killingTerminates a selected processLoss of that process and its data
Reclaim strategies compared

If the working sets of active processes no longer fit in RAM, the system spends most of its time moving pages in and out, a state called thrashing. Response times then rise sharply even though the processor appears busy, and adding RAM or reducing the workload is the only lasting fix.

Common misconceptions and pitfalls

Memory figures in system monitors are easy to misread, and many tuning mistakes come from treating every used byte as a problem. Experienced administrators interpret them in the context of how the kernel actually manages memory.

  • Unused RAM is wasted RAM: a high share used for file cache is healthy, because cache is released instantly when programs need memory.
  • Disabling swap rarely helps: it removes a safety margin and can trigger out-of-memory termination sooner.
  • Memory leaks grow slowly: a process whose private memory rises steadily over days usually leaks rather than caches.
  • Virtual size is not usage: the reserved address space of a process can far exceed the RAM it really occupies.

In everyday language

Memory management is the operating system acting as a careful librarian for the computer’s working memory. Every program asks for space to keep its data while it runs. The system gives each program its own set of shelves, makes sure no program can reach into another one’s shelves, and takes the space back when a program closes.

When space runs short, the system makes room. It throws away copies it can fetch again later, packs rarely used items tightly or moves them to the disk, and only as a last resort closes a program to keep the whole computer working.

Seen in the real world

A video editor works on a laptop with 16 GB of RAM and keeps the editing program, a web browser with 40 tabs and a messaging app open. While rendering a 4K project, the system becomes sluggish and the disk activity light stays on.

The system monitor shows that memory is almost fully used and that the page file is growing quickly, a sign of heavy paging. The editor closes the browser, which frees about 5 GB, and the render speed returns to normal. After upgrading to 32 GB of RAM, the same workload runs with room to spare, and paging activity during renders practically disappears.