ENع
←Segmentation and free space
Lesson 30 · Memory management

Segmentation and free-space management

14 min11 steps5 questionsIntermediate
About this lesson

Base and bounds, from the lesson Address spaces, base and bounds, moves a whole address space as one block, including the big unused gap between heap and stack. Segmentation fixes that: the MMU keeps a base and a size for each segment, so code, heap and stack can each live anywhere. Follow four reads from the OSTEP worked example as the MMU splits each address into a segment number and an offset, adds a base, checks a size, and once refuses with a segmentation fault. Then watch what variable-sized segments do to physical memory: holes, external fragmentation, and the kernel's free list with best fit, splitting and coalescing. The Hardware lesson on virtual memory covers the chip's side of address translation.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 30 · Interactive
01 / 11

Three pieces, three places

A program uses three pieces of memory: code, heap and stack, with an unused gap in between. Base and bounds moves the whole thing, gap and all. Segmentation places each piece on its own, so the gap costs nothing.

virtual address space (16 KB)      physical memory (64 KB)
  0K- 2K  code                      0K-16K  kernel
  2K- 4K  unused                   26K-28K  stack
  4K- 7K  heap                     32K-34K  code
  7K-14K  unused gap               34K-37K  heap
 14K-16K  stack

base and bounds: all 16 KB in one block, gaps included
segmentation:    only the 7 KB in use takes memory
Loading figure…
or ← →
Read the lesson step by step
  1. Three pieces, three places

    A program uses three pieces of memory: code, heap and stack, with an unused gap in between. Base and bounds moves the whole thing, gap and all. Segmentation places each piece on its own, so the gap costs nothing.

    virtual address space (16 KB)      physical memory (64 KB)
      0K- 2K  code                      0K-16K  kernel
      2K- 4K  unused                   26K-28K  stack
      4K- 7K  heap                     32K-34K  code
      7K-14K  unused gap               34K-37K  heap
     14K-16K  stack
    
    base and bounds: all 16 KB in one block, gaps included
    segmentation:    only the 7 KB in use takes memory
  2. The kernel fills the table

    The MMU, the part of the CPU that translates addresses, keeps one base and one size per segment, plus which way it grows. The kernel writes these registers before it runs the program. Only the kernel may change them.

    segment  bits  base  size  grows
    code     00    32K   2K    up
    heap     01    34K   3K    up
    stack    11    28K   2K    down
    
    a virtual address: 14 bits
      top 2 bits   which segment
      low 12 bits  offset inside it (so at most 4 KB)
  3. Line 1: a code address

    Address 100 starts with bits 00, so it is in the code segment, at offset 100. The MMU checks 100 is below the size, 2 KB, then adds the base, 32 KB: physical address 32868.

    line 1   a = mem[100]
    100    = 00 000001100100
    bits   00 -> code     offset 100
    check  100 < 2048            ok
    add    32768 + 100 = 32868
  4. Line 2: a heap address

    Address 4200 starts with bits 01: the heap. The offset is what is left, 4200 minus 4096, which is 104. It is below 3 KB, so the MMU adds the heap's base, 34 KB: physical address 34920.

    line 2   b = mem[4200]
    4200   = 01 000001101000
    bits   01 -> heap     offset 104  (4200 - 4096)
    check  104 < 3072            ok
    add    34816 + 104 = 34920
    
    wrong way: 34816 + 4200 = 39016 (past the heap)
  5. Line 3: the stack grows down

    Address 15360 starts with 11: the stack, offset 3072. The stack grows down, so the MMU counts back from the top of a 4 KB segment: 3072 minus 4096 is -1024. Base 28 KB minus 1 KB: physical 27648.

    line 3   c = mem[15360]
    15360  = 11 110000000000   (hex 0x3C00)
    bits   11 -> stack    offset 3072
    grows down: 3072 - 4096 = -1024
    check  |-1024| <= 2048       ok
    add    28672 - 1024 = 27648  (27 KB)
  6. Line 4: past the end

    Address 7168 starts with 01: the heap, offset 3072. But the heap is only 3 KB, so offsets stop at 3071. The MMU refuses the read and traps to the kernel, which ends the program. This is a segmentation fault.

    line 4   d = mem[7168]
    7168   = 01 110000000000
    bits   01 -> heap     offset 3072
    check  3072 < 3072?        NO -> fault
    trap   into the kernel; the program is ended
    
    on Linux today: signal SIGSEGV, and the shell prints
    Segmentation fault
  7. Freed memory becomes holes

    Our program has ended, so the kernel takes back its segments. Code and heap sat side by side and become one 5 KB hole; the stack leaves a 2 KB hole. The kernel keeps every hole in a list, the free list.

    free list (address order)
      16K  6 KB
      26K  2 KB
      32K  5 KB
      48K  3 KB
    total free   16 KB
    largest      6 KB
  8. Enough memory, no room

    A new 8 KB segment arrives. 16 KB is free, but the biggest hole is 6 KB, and a segment must be one unbroken piece. So the request must wait. This waste between used blocks is called external fragmentation.

    request   8 KB, in one piece
    free      6 + 2 + 5 + 3 = 16 KB
    largest   6 KB  -> no hole fits
    
    a program asks the kernel for memory like this
    (C99 + POSIX; mmap fails with ENOMEM when it cannot):
    
    #define _DEFAULT_SOURCE   /* MAP_ANONYMOUS on Linux */
    #include <stdio.h>
    #include <sys/mman.h>
    
    int main(void) {
        size_t len = 8 * 1024;                       /* ask for 8 KB */
        char *p = mmap(NULL, len, PROT_READ | PROT_WRITE,
                       MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
        if (p == MAP_FAILED) {                       /* e.g. ENOMEM */
            perror("mmap");
            return 1;
        }
        p[0] = 'x';                                  /* use it */
        printf("got 8 KB\n");
        munmap(p, len);                              /* give it back */
        return 0;
    }
  9. Picking a hole: best fit

    A 4 KB segment arrives. First fit would take the first hole big enough, at 16K. Best fit takes the smallest hole that fits: 5 KB at 32K. The kernel splits it: 4 KB used, 1 KB stays free.

    request 4 KB      holes: 16K(6) 26K(2) 32K(5) 48K(3)
    first fit   first big enough     -> 16K
    best fit    smallest big enough  -> 32K   (chosen)
    worst fit   largest              -> 16K
    
    split   32K-36K used, 36K-37K free
    free list now
      16K  6 KB
      26K  2 KB
      36K  1 KB
      48K  3 KB
  10. Merging neighbours

    Program B ends. Its 4 KB sits between the 6 KB hole and the 2 KB hole. The kernel checks the neighbours of every freed block and merges free ones, so three small holes become one 12 KB hole. This is coalescing.

    free 22K-26K (program B)
    left  neighbour 16K-22K free -> merge
    right neighbour 26K-28K free -> merge
    
    without merging: 6 + 4 + 2 KB, three pieces
    with merging:    one 12 KB hole at 16K
    free list now
      16K  12 KB
      36K  1 KB
      48K  3 KB
  11. Now it fits

    The waiting 8 KB segment tries again. The 12 KB hole is the only one big enough, so it goes at 16K and 4 KB stays free. The kernel writes the new base and size into that program's segment table.

    the whole free list as a Python simulation:
    
    free = [[16, 6], [26, 2], [32, 5], [48, 3]]   # holes: [start KB, size KB]
    
    def alloc(n):                     # best fit, then split
        fits = [h for h in free if h[1] >= n]
        if not fits:
            return None
        h = min(fits, key=lambda h: h[1])
        at = h[0]
        h[0] += n; h[1] -= n
        if h[1] == 0:
            free.remove(h)
        return at
    
    def release(at, n):               # free, then coalesce
        free.append([at, n]); free.sort()
        i = 0
        while i < len(free) - 1:
            if free[i][0] + free[i][1] == free[i + 1][0]:
                free[i][1] += free.pop(i + 1)[1]
            else:
                i += 1
    
    print(alloc(8))      # no hole is 8 KB
    print(alloc(4))      # best fit: the 5 KB hole
    release(22, 4)       # program B ends
    print(free)
    print(alloc(8))
    
    prints:
    None
    32
    [[16, 12], [36, 1], [48, 3]]
    16

Quiz Unlocks after the last step.