TExcelTAD
Home › Operating Systems: Linux & Windows › Memory Management

Memory Management

Every program you run needs memory for its code, its variables and the data it is working on. The operating system owns all of the physical RAM and decides who gets which piece, when, and for how long. This lesson covers the big picture: what a process's memory looks like, how memory is handed out (by the kernel and by user-space allocators), and why fragmentation makes the job hard. The next lessons go deeper into Virtual Memory & Paging, Page Replacement and Swap & the Page File.

The memory manager's jobs

Job What it means Linux Windows
Isolation One process can't read or corrupt another's memory Per-process page tables, mm_struct Per-process page tables, VAD tree
Allocation Hand out memory on request, take it back when freed brk, mmap, page allocator, slab VirtualAlloc, heap manager, pool allocator
Sharing Let processes share code (libraries) and data on purpose Shared mappings, page cache Section objects, mapped DLLs
Over-subscription Run more than fits in RAM Swap, overcommit Page file, commit charge
Caching Use idle RAM to cache files Page cache Standby list (system cache)

A modern OS never gives a process raw physical addresses. Each process gets its own virtual address space, and the hardware (the MMU) translates every access to a physical address using tables the kernel maintains. That is the topic of the next lesson; here we look at what lives inside one address space.

The layout of a process

On both systems a 64-bit process sees a huge, mostly empty virtual address space. Only some regions are actually mapped:

text
 high addresses
 +-----------------------------+  <- kernel half (not accessible from user mode)
 |        kernel space         |
 +=============================+  <- top of user space (0x00007fff_ffffffff on x86-64)
 |   stack (main thread)       |  grows down; each thread has its own stack
 |             |               |
 |             v               |
 |                             |
 |   memory-mapped region      |  shared libraries (.so / .dll), mmap'd files,
 |   (mmap / VirtualAlloc)     |  large allocations, thread stacks
 |                             |
 |             ^               |
 |             |               |
 |   heap                      |  malloc / new / HeapAlloc; grows up
 +-----------------------------+
 |   .bss  (zeroed globals)    |
 |   .data (initialised globals)|
 |   .text (machine code)      |  read + execute only
 +-----------------------------+
 low addresses (page 0 is never mapped: catches NULL pointers)
  • Text is mapped read+execute and shared between every process running the same program.
  • Data and BSS hold global variables. BSS costs nothing on disk: the OS just maps zero-filled pages.
  • Heap grows upwards as the program allocates. Stack holds function frames and local variables.
  • Address space layout randomisation (ASLR) shifts each region to a random base on every run (Linux and Windows both do this), which is why exact addresses are never the same twice.

On Linux you can see the mapped regions of any process in /proc/<pid>/maps. The addresses change with every run, so this example prints only the permissions and name of the stack region of awk itself:

bash · try it yourself
awk '$6 == "[stack]" {print $2, $6}' /proc/self/maps
echo "page size: $(getconf PAGESIZE) bytes"
rw-p [stack]
page size: 4096 bytes

rw-p means readable, writable, not executable and private (copy-on-write, not shared). A stack that is not executable is one of the cheapest protections against code-injection attacks: Windows calls it DEP, Linux the NX bit.

The kernel also keeps per-process memory counters. Their values differ on every machine, so we only list the names of the Vm* fields in /proc/self/status:

bash · try it yourself
grep -o '^Vm[A-Za-z]*' /proc/self/status | tr '\n' ' '
echo
VmPeak VmSize VmLck VmPin VmHWM VmRSS VmData VmStk VmExe VmLib VmPTE VmSwap
Field Meaning Windows counterpart (Task Manager / Get-Process)
VmSize Total virtual address space mapped Virtual size (VirtualMemorySize64)
VmRSS Resident set: pages currently in RAM Working set (WorkingSet64)
VmHWM Peak resident set ("high water mark") Peak working set
VmData Private data + heap Private bytes / commit size (PrivateMemorySize64)
VmStk Main stack part of private bytes
VmSwap Pages of this process now in swap part of commit, not in working set

On Windows the same numbers come from the process object (sample output, yours will differ):

powershell
PS C:\Users\ada> Get-Process notepad | Format-List Name, WorkingSet64, PrivateMemorySize64, VirtualMemorySize64

Name                : Notepad
WorkingSet64        : 74563584
PrivateMemorySize64 : 18620416
VirtualMemorySize64 : 2203906166784

The enormous virtual size is normal: 64-bit Windows processes reserve large address ranges they never use.

Two levels of allocation

When your C program calls malloc(100) or your Python program creates a list, two allocators are involved:

text
  your code:   malloc / new / HeapAlloc / Python objects
                   |
  user-space allocator (glibc malloc, musl mallocng, Windows heap manager / segment heap)
                   |  asks the kernel for big chunks only
  system calls:    brk / mmap (Linux)          VirtualAlloc / NtAllocateVirtualMemory (Windows)
                   |
  kernel:          virtual memory areas  ->  page allocator (buddy system)  ->  physical frames
  • The user-space allocator carves small blocks out of big regions so that most malloc calls never enter the kernel. glibc grows the heap with brk and serves large requests (128 KiB+ by default) with a separate mmap.
  • On Windows, VirtualAlloc works in two steps: reserve a range of addresses (no memory yet) and then commit pages (memory is promised, counted against the commit limit). The heap manager (HeapAlloc, used by malloc in the C runtime) sits on top.
  • The kernel's own allocator hands out physical page frames with a buddy allocator (both kernels use power-of-two blocks of pages), and small kernel objects with a slab allocator (Linux SLUB) or the pool allocator (Windows paged and non-paged pool).

Allocating virtual memory does not consume RAM yet. Physical frames are attached lazily, the first time a page is touched (a page fault). This is called demand paging.

Fragmentation and placement strategies

Allocators must decide where a request goes. Picking badly leaves memory split into gaps too small to use:

  • External fragmentation: enough free memory in total, but no single hole is big enough.
  • Internal fragmentation: a block bigger than requested is handed out and the rest is wasted inside it.

Classic placement strategies for a list of free holes:

Strategy Picks Trade-off
First fit The first hole that is big enough Fast; leaves small holes at the start
Best fit The smallest hole that is big enough Less waste per request; creates tiny unusable slivers
Worst fit The largest hole Leaves big remainders; usually worst in practice

This simulation manages a 100 KB region with first fit and best fit and replays the same sequence of requests:

python · try it yourself
def simulate(strategy, size, requests):
    free = [(0, size)]                       # list of (start, length) holes
    used = {}
    for op, name, amount in requests:
        if op == "free":
            start, length = used.pop(name)
            free.append((start, length))
            free.sort()
            merged = [free[0]]               # coalesce neighbouring holes
            for s, l in free[1:]:
                ps, pl = merged[-1]
                if ps + pl == s:
                    merged[-1] = (ps, pl + l)
                else:
                    merged.append((s, l))
            free = merged
            continue
        fits = [h for h in free if h[1] >= amount]
        if not fits:
            print(f"  {name:>2} {amount:>3}K  FAILED (holes: {[l for _, l in free]})")
            continue
        hole = fits[0] if strategy == "first" else min(fits, key=lambda h: h[1])
        free.remove(hole)
        used[name] = (hole[0], amount)
        if hole[1] > amount:
            free.append((hole[0] + amount, hole[1] - amount))
            free.sort()
        print(f"  {name:>2} {amount:>3}K  at {hole[0]:>3}K")
    print("  free holes:", [l for _, l in free])

requests = [("alloc", "A", 20), ("alloc", "B", 15), ("alloc", "C", 30),
            ("alloc", "D", 10), ("free", "A", 0), ("free", "C", 0),
            ("alloc", "E", 12), ("alloc", "F", 25), ("alloc", "G", 30)]
for strategy in ("first", "best"):
    print(f"{strategy} fit:")
    simulate(strategy, 100, requests)
first fit:
   A  20K  at   0K
   B  15K  at  20K
   C  30K  at  35K
   D  10K  at  65K
   E  12K  at   0K
   F  25K  at  35K
   G  30K  FAILED (holes: [8, 5, 25])
  free holes: [8, 5, 25]
best fit:
   A  20K  at   0K
   B  15K  at  20K
   C  30K  at  35K
   D  10K  at  65K
   E  12K  at   0K
   F  25K  at  75K
   G  30K  at  35K
  free holes: [8]

Both strategies put E at 0K, but they disagree about F (25K): first fit takes the first hole that is big enough (the 30K hole left by C) and so has no 30K hole left for G, while best fit uses the exactly-sized 25K hole at 75K and keeps the 30K hole intact. Try other request sizes: neither strategy wins every sequence.

The buddy allocator

Linux's page allocator (visible in /proc/buddyinfo) and the Windows memory manager both work with blocks of 2n pages. A request is rounded up to a power of two; a bigger block is split in half repeatedly into "buddies"; when a block is freed and its buddy is also free, the two merge back. Finding a buddy is a single XOR of the block address with its size, which makes the scheme fast and keeps external fragmentation in check, at the price of internal fragmentation (a 33-page request gets 64 pages).

python · try it yourself
class Buddy:
    def __init__(self, order):
        self.max = order
        self.free = {o: [] for o in range(order + 1)}
        self.free[order].append(0)            # one block covering everything
        self.owner = {}

    def alloc(self, name, pages):
        order = max(0, (pages - 1).bit_length())  # round up to a power of two
        o = order
        while o <= self.max and not self.free[o]:
            o += 1
        if o > self.max:
            print(f"alloc {name} ({pages} pages): out of memory")
            return
        addr = self.free[o].pop(0)
        while o > order:                       # split, keep the upper half free
            o -= 1
            self.free[o].append(addr + (1 << o))
            self.free[o].sort()
        self.owner[name] = (addr, order)
        print(f"alloc {name} ({pages:>2} pages) -> block {addr:>2}..{addr + (1 << order) - 1:<2} "
              f"(size {1 << order})  {self.show()}")

    def release(self, name):
        addr, order = self.owner.pop(name)
        while order < self.max:
            buddy = addr ^ (1 << order)        # the buddy differs in exactly one bit
            if buddy not in self.free[order]:
                break
            self.free[order].remove(buddy)
            addr = min(addr, buddy)
            order += 1
        self.free[order].append(addr)
        self.free[order].sort()
        print(f"free  {name}                                  {self.show()}")

    def show(self):
        return "free: " + " ".join(f"{1 << o}x{len(v)}" for o, v in self.free.items() if v)

b = Buddy(5)          # 32 pages
b.alloc("A", 5)
b.alloc("B", 3)
b.alloc("C", 8)
b.release("A")
b.release("B")
b.release("C")
alloc A ( 5 pages) -> block  0..7  (size 8)  free: 8x1 16x1
alloc B ( 3 pages) -> block  8..11 (size 4)  free: 4x1 16x1
alloc C ( 8 pages) -> block 16..23 (size 8)  free: 4x1 8x1
free  A                                  free: 4x1 8x2
free  B                                  free: 8x1 16x1
free  C                                  free: 32x1

A asked for 5 pages but received 8 (internal fragmentation). After all three blocks are released, every buddy pair merges and the allocator is back to a single 32-page block.

On a real Linux box, /proc/buddyinfo shows how many free blocks of each order (1, 2, 4 … 1024 pages) every memory zone has (sample output, yours will differ):

bash
ada@ubuntu:~$ cat /proc/buddyinfo
Node 0, zone      DMA      0      0      0      0      0      0      0      0      1      1      2
Node 0, zone    DMA32      6      5      7      6      8      7      5      6      5      4    410
Node 0, zone   Normal    812    590    402    251    120     61     30     14      9      6   2981

Limits per process

Both systems let you cap how much memory a process may use. In bash, ulimit -v limits the virtual address space (in KiB) of the shell and its children; a subshell keeps the change from leaking out:

bash · try it yourself
( ulimit -v 102400; echo "inside the subshell: $(ulimit -v) KiB" )
echo "outside: $(ulimit -v)"
inside the subshell: 102400 KiB
outside: unlimited

Production Linux systems usually use cgroups instead (memory.max in a systemd unit or a container). Windows uses job objects (SetInformationJobObject with a process memory limit), which is also how Docker on Windows caps a container.

Note: Python, Java and .NET programs have their own allocators and garbage collectors on top of all this. They request big arenas from the OS and often keep them after objects die, so "memory used" in Task Manager or top can stay high even after the program freed its objects.

Learn more: Virtual Memory & Paging · Processes · /proc & /sys

Test yourself

On Windows, what is the difference between reserving and committing memory with VirtualAlloc?

  1. Reserving allocates RAM, committing writes it to disk
  2. Reserving claims an address range only; committing makes the pages usable and counts them against the commit limit
  3. They are the same operation with different names
  4. Committing is only possible for kernel drivers

A buddy allocator receives a request for 9 pages. How many pages does the block it returns contain?

  1. 9
  2. 10
  3. 16
  4. 32

Which /proc/<pid>/status field corresponds to a Windows process's working set?

  1. VmSize
  2. VmRSS
  3. VmStk
  4. VmLib