Segmentation and free-space management
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.
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
Read the lesson step by step
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 memoryThe 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)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 = 32868Line 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)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)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 faultFreed 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 KBEnough 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; }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 KBMerging 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 KBNow 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
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01With 14-bit addresses whose top two bits pick the segment (00 code, 01 heap, 11 stack), which segment is virtual address 4200 in, and at what offset?
4200 is 01 0000 0110 1000 in binary. The top bits 01 mean the heap, and the low 12 bits are 4200 minus 4096, which is 104. With the heap's base at 34 KB, the physical address is 34816 + 104 = 34920.
02The heap segment has size 3 KB. What happens on a read of virtual address 7168 (bits 01, offset 3072)?
A 3 KB segment has offsets 0 to 3071. Offset 3072 fails the bounds check, so the hardware traps into the kernel, which usually ends the program. That is where the name segmentation fault comes from.
03Free holes are 6, 2, 5 and 3 KB (16 KB in total). Why can a request for one 8 KB segment still fail?
A segment needs one contiguous range of physical memory. The free space is real but split into pieces, none big enough. That waste between allocated blocks is external fragmentation.
04The free list (in address order) holds holes of 6 KB at 16K, 2 KB at 26K, 5 KB at 32K and 3 KB at 48K. Where does best fit put a 4 KB segment?
Best fit picks the smallest hole that can hold the request: 5 KB at 32K. It splits it, using 32K to 36K and leaving a 1 KB hole at 36K. First fit and worst fit would both pick the 6 KB hole at 16K here.
05A 4 KB block at 22K is freed. The ranges 16K to 22K and 26K to 28K are already free. What does coalescing do?
When memory is freed, the kernel checks the free ranges right next to it and merges them. 6 + 4 + 2 KB becomes one 12 KB hole, big enough for requests no single piece could hold. Moving programs would be compaction, which is far slower.
Glossary
- Segment
- One contiguous piece of a program's address space, such as its code, heap or stack, placed in physical memory on its own.
- Segment table
- The MMU's registers that hold a base, a size and a growth direction for each segment. Only the kernel may change them.
- Offset
- The part of a virtual address after the segment bits: how far into the segment the byte is.
- Segmentation fault
- The trap the MMU raises when an address is outside its segment. The kernel usually ends the program. The name stayed even on machines that no longer use segments.
- External fragmentation
- Free memory split into holes between used blocks, so a request can fail even though enough memory is free in total.
- Free list
- The kernel's list of free holes, each with a start address and a size, usually kept in address order.
- Best fit
- A placement policy that picks the smallest free hole big enough for the request. First fit picks the first one big enough; worst fit picks the largest.
- Coalescing
- Merging a freed block with the free holes right next to it, so small holes become one bigger hole.
Notes and sources
- The segment table, the four addresses and their translations are the worked example from OSTEP chapter 16: a pretend 16 KB address space with 14-bit addresses in a 64 KB machine. Programs B and C and the two new segments are added for the free-space part.
- mem[a] on the card is shorthand for "read the byte at virtual address a". In C it would be a pointer read; either way the CPU sends the virtual address to the MMU.
- OSTEP counts the stack segment back from a 4 KB maximum segment size, because 12 offset bits can name at most 4096 bytes. The bounds check for a downward segment is that the negative offset is no bigger than the segment size.
- Today x86-64 and RISC-V systems manage memory with paging, the next lesson, which uses fixed-size pages so free space is just a list of equal pieces. On x86 segmentation cannot be switched off, so systems such as Linux set every segment to cover all of memory. The name segmentation fault stayed.
- Real kernels place memory with variations of these ideas: xv6, MIT's teaching kernel, keeps a linked free list of 4096-byte pages, and Linux hands out physical pages with a buddy allocator that splits blocks in half and coalesces freed buddies.
- A kernel could also fix fragmentation by compaction: stopping programs, copying their segments together and updating their bases. Copying is slow, so free-list policies that keep big holes available are used instead.
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 16: Segmentation
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 17: Free-Space Management
- Berkeley CS162, Lecture 14: Memory 1: Virtual Memory, Segments and Page Tables
- MIT 6.1810 xv6 source: kernel/kalloc.c (the physical page free list)
- M. Gorman, Understanding the Linux Virtual Memory Manager, ch. 6: Physical Page Allocation (kernel.org)
- Linux man-pages: mmap(2)
Quiz Unlocks after the last step.