Lesson 4 · Memory management

Segmentation and Paging

Segmentation and paging both let a program use logical addresses that the hardware maps to physical memory. Segments follow the program's structure and vary in size; pages are one fixed size chosen by the hardware. That one choice decides which kind of memory gets wasted.

Segmentation and Paging concept diagramA visual explanation of the layout and operations shown in this lesson.segmentation — variable sizepaging — one fixed sizecode · 6 KBfree holedata · 4 KBfree holestack · 3 KBpage 0 · 4 KBpage 1 · 4 KBpage 2 · 4 KBpage 3 · 4 KBpage 4 · 4 KBpage 5 · 4 KB (2 KB used)holes between segmentsexternal fragmentation13 KB into 4 pages of 4 KB — 3 KB unused inside page 5internal fragmentation, never external
1

The Problem Both Solve

The simplest scheme gives each process one contiguous block of physical memory, described by a base register and a limit register. Translation is one comparison and one addition. It fails on external fragmentation: processes of different sizes come and go and leave free holes between live blocks, until there is plenty of free memory in total but no single hole big enough for the next process.

Placement rules such as first fit, best fit and worst fit only decide which hole to use; none of them stops holes from forming. Compaction, sliding live blocks together, merges the holes but copies memory while the processes wait. Segmentation and paging are the two ways of not needing one big contiguous block in the first place.

  • Both schemes map a logical address, the one the program uses, to a physical address in RAM on every memory access
  • The mapping is done by the CPU's memory management unit (MMU), with tables the operating system fills in
2

Segmentation

  1. Split the logical address into a segment number s and an offset d
  2. Look up segment s in the segment table: base, limit and permissions
  3. If d ≥ limit, or the access breaks the permissions, trap to the operating system
  4. Otherwise the physical address is base + d

Segmentation divides a program's memory into variable-size parts that match its structure: code, data, stack, each shared library. Each part has its own row in the segment table, with a base, a limit and permissions, so code can be read-only and executable while data is read-write.

With segment 1 at base 1400 and limit 400, the address (1, 53) passes the check and maps to 1400 + 53 = 1453. The address (1, 500) fails it, because 500 ≥ 400, and the hardware traps before any memory is read. That trap is where the name segmentation fault comes from. Sharing is natural too: one copy of a library's code segment can appear in many processes' segment tables.

The weakness is the variable size. Allocating and freeing segments of different lengths leaves holes between them, so segmentation brings back the external fragmentation of contiguous allocation, just in smaller pieces.

  • The limit check protects other memory on every access, which is what makes segments a protection mechanism and not just a layout
  • A segment must still be contiguous in physical memory, so a large one needs a large hole
3

Paging

  1. Split the logical address: page number p = high bits, offset d = low bits
  2. Look up page p in the page table; if its entry is not valid, raise a page fault
  3. Read the frame number f from the entry
  4. The physical address is f × page size + d

Paging cuts logical memory into fixed-size pages and physical memory into frames of the same size, usually 4 KB, and the page table maps each page to any free frame. Because every frame fits every page, there are no awkward holes: external fragmentation disappears.

With 32-byte pages, logical address 100 is page 3, offset 4 (100 = 3 × 32 + 4). If the page table maps page 3 to frame 7, the physical address is 7 × 32 + 4 = 228. Page sizes are powers of two so that this split is free: the low 5 bits are the offset and the rest is the page number, with no division at all.

The cost is internal fragmentation: the last page of a region is usually only partly used. A 4,100-byte region needs two 4 KB pages and leaves 4,092 bytes of the second one empty. That waste is bounded at less than one page per region, while external fragmentation has no such bound. The other cost is the page-table lookup on every access, which the translation lookaside buffer hides by caching recent translations.

  • A page that is not in memory has an invalid entry; touching it raises a page fault, which is how demand paging loads pages lazily
  • Large address spaces split the table into levels: multilevel paging
Key reference

Terms, operations, and practical uses

Segmentation

  • SegmentA variable-length logical unit: code, data, stack, library.
  • Segment tableBase, limit, and permissions for each segment.
  • Segmentation faultAn access beyond a segment's limit.
  • The flawVariable sizes bring back external fragmentation.

Paging

  • Page and frameFixed-size units, virtual and physical, usually 4 KB.
  • Any frame fitsUniform size eliminates external fragmentation entirely.
  • Bit slicingPage sizes are powers of two, so the page number and offset are just the high and low bits.

Fragmentation

  • ExternalFree memory stranded in scattered, unusable holes.
  • InternalThe unused tail of a region's last page: under one page per region.
  • Segmented pagingSegments for structure, pages underneath; x86 offered it, operating systems mostly used flat segments.
  • x86-64Dropped segmentation apart from FS/GS for thread-local storage.
Implementation

Translate one address, then place three regions

PAGE = 32
PAGE_TABLE = {0: 9, 1: 4, 2: 11, 3: 7}     # page number -> frame number
SEGMENTS = {1: (1400, 400)}                # segment -> (base, limit)


def translate_paged(logical):
    page, offset = divmod(logical, PAGE)   # high bits, low 5 bits
    if page not in PAGE_TABLE:
        return None                        # page fault
    return PAGE_TABLE[page] * PAGE + offset


def translate_segmented(seg, offset):
    base, limit = SEGMENTS[seg]
    if offset >= limit:
        return None                        # trap: past the segment's end
    return base + offset


print("paged 100 ->", translate_paged(100))
print("segment (1, 53) ->", translate_segmented(1, 53))
print("segment (1, 500) ->", translate_segmented(1, 500) or "trap")

# Segments A 60, B 40, C 30 in 160 bytes; B is freed, then D asks for 50.
holes = [40, 30]
request = 50
fits = any(h >= request for h in holes)
print(f"segments: {sum(holes)} B free, largest hole {max(holes)} B, "
      f"{request} B request {'placed' if fits else 'refused'}")

# The same regions as pages: only the tail of each last page is wasted.
regions = [60, 40, 30]
wasted = sum(-r % PAGE for r in regions)
print(f"pages: {wasted} B wasted inside last pages")
#include <algorithm>
#include <iostream>
#include <map>
#include <vector>
using namespace std;

const int PAGE = 32;
map<int, int> PAGE_TABLE{{0, 9}, {1, 4}, {2, 11}, {3, 7}};  // page -> frame
map<int, pair<int, int>> SEGMENTS{{1, {1400, 400}}};       // segment -> {base, limit}

int translatePaged(int logical) {
    int page = logical / PAGE, offset = logical % PAGE;     // high bits, low 5 bits
    auto it = PAGE_TABLE.find(page);
    if (it == PAGE_TABLE.end()) return -1;                  // page fault
    return it->second * PAGE + offset;
}

int translateSegmented(int seg, int offset) {
    auto [base, limit] = SEGMENTS[seg];
    if (offset >= limit) return -1;                         // trap: past the segment's end
    return base + offset;
}

int main() {
    cout << "paged 100 -> " << translatePaged(100) << "\n";
    cout << "segment (1, 53) -> " << translateSegmented(1, 53) << "\n";
    int bad = translateSegmented(1, 500);
    cout << "segment (1, 500) -> " << (bad < 0 ? "trap" : to_string(bad)) << "\n";

    // Segments A 60, B 40, C 30 in 160 bytes; B is freed, then D asks for 50.
    vector<int> holes{40, 30};
    int request = 50, freeBytes = 0, largest = 0;
    bool fits = false;
    for (int h : holes) {
        freeBytes += h;
        largest = max(largest, h);
        if (h >= request) fits = true;
    }
    cout << "segments: " << freeBytes << " B free, largest hole " << largest << " B, "
         << request << " B request " << (fits ? "placed" : "refused") << "\n";

    // The same regions as pages: only the tail of each last page is wasted.
    int wasted = 0;
    for (int r : {60, 40, 30}) wasted += (PAGE - r % PAGE) % PAGE;
    cout << "pages: " << wasted << " B wasted inside last pages\n";
}
import java.util.Map;

class Main {
    static final int PAGE = 32;
    static final Map<Integer, Integer> PAGE_TABLE = Map.of(0, 9, 1, 4, 2, 11, 3, 7);  // page -> frame
    static final Map<Integer, int[]> SEGMENTS = Map.of(1, new int[]{1400, 400});     // segment -> {base, limit}

    static int translatePaged(int logical) {
        int page = logical / PAGE, offset = logical % PAGE;   // high bits, low 5 bits
        Integer frame = PAGE_TABLE.get(page);
        if (frame == null) return -1;                         // page fault
        return frame * PAGE + offset;
    }

    static int translateSegmented(int seg, int offset) {
        int[] s = SEGMENTS.get(seg);
        if (offset >= s[1]) return -1;                        // trap: past the segment's end
        return s[0] + offset;
    }

    public static void main(String[] args) {
        System.out.println("paged 100 -> " + translatePaged(100));
        System.out.println("segment (1, 53) -> " + translateSegmented(1, 53));
        int bad = translateSegmented(1, 500);
        System.out.println("segment (1, 500) -> " + (bad < 0 ? "trap" : String.valueOf(bad)));

        // Segments A 60, B 40, C 30 in 160 bytes; B is freed, then D asks for 50.
        int[] holes = {40, 30};
        int request = 50, freeBytes = 0, largest = 0;
        boolean fits = false;
        for (int h : holes) {
            freeBytes += h;
            largest = Math.max(largest, h);
            if (h >= request) fits = true;
        }
        System.out.println("segments: " + freeBytes + " B free, largest hole " + largest + " B, "
            + request + " B request " + (fits ? "placed" : "refused"));

        // The same regions as pages: only the tail of each last page is wasted.
        int wasted = 0;
        for (int r : new int[]{60, 40, 30}) wasted += (PAGE - r % PAGE) % PAGE;
        System.out.println("pages: " + wasted + " B wasted inside last pages");
    }
}
Watch it run

Step through it

Running on logical 100, 32-byte pages; segment 1 = base 1400, limit 400; regions 60, 40, 30

paging, 32-byte pages: translate logical 100logical address100page table0: frame 91: frame 42: frame 113: frame 74: not valid5: not validphysical framesframe 0frame 1frame 2frame 3frame 4frame 5frame 6frame 7page size 32 = 2⁵ bytes, so the low 5 bits are the offsetnothing has been looked up yet
Step 1

The program emits address 100

The CPU issues logical address 100. The program sees memory as one flat range starting at 0; where the byte really lives is decided by the MMU on every access, using a page table the operating system filled in.

Output
1 / 13
4

Paging vs Segmentation

The two schemes make opposite choices about one thing, who decides the size of a unit, and every other difference follows from it:

Paging vs segmentation
SegmentationPaging
Unit sizevariable, set by the program's structurefixed, set by the hardware (often 4 KB)
Address(segment, offset)one number split into page and offset
Table entrybase, limit, permissionsframe number, valid bit, permissions
External fragmentationyesno
Internal fragmentationalmost noneunder one page per region
Protection followslogical parts (code, data, stack)4 KB pages
Visible to the programmeryes, in the address formno, addresses look flat
  • Segmentation fits how programmers think; paging fits how memory is allocated
  • Moving a whole segment needs one base change; moving a page needs one table entry change
5

Segmented Paging and x86 Segmentation

Segmented paging combines the two: the address names a segment for structure and protection, the limit is checked, and then the segment itself is paged, so it no longer needs contiguous physical memory. MULTICS worked this way, and 32-bit x86 had both a segmentation unit and a paging unit in series.

In practice operating systems hardly used x86 segmentation. Linux and Windows gave every segment base 0 and a limit covering the whole address space, a flat model that effectively switched segmentation off and left all the real work to paging. Portable code could not depend on x86 segment registers anyway.

x86-64 made that official. In 64-bit mode the base and limit of the code, data and stack segments are ignored. Only FS and GS keep a usable base, because operating systems use them to find thread-local storage. The protection that segments were meant to give now comes from permission bits in each page table entry: read/write, user/supervisor and no-execute.