Segmentation
The segment abstraction
Segmentation divides a programme’s address space into logical segments — named, variable-sized regions that correspond to parts of the programme: code, data, stack, heap. Each segment is a contiguous region of physical memory with its own base and limit. A logical address is a pair (segment_number, offset).
The programmer or compiler is conscious of segments; they reflect the programme’s logical structure, not just a flat byte array.
Segment table
Each process has a segment table stored in the MMU or in memory (indexed by the segment-table base register, STBR). Each entry holds:
| Field | Meaning |
|---|---|
| Base | Physical address of the segment’s start |
| Limit | Length of the segment in bytes |
| Protection bits | Read, write, execute permissions |
Address translation: physical address = base[segment] + offset. The offset must satisfy offset < limit[segment], else a segmentation fault is raised.
Advantages over flat address spaces
- Natural sharing: the code segment can be shared between processes (read-only, same base/limit).
- Natural protection: segments are different memory types — code is read-execute, data is read-write, stack is read-write and grows. Separate segments make different protection policies natural.
- Independent growth: the heap and stack can grow independently (each expands when its limit is hit and more memory is allocated). A flat address space forces them to grow towards each other.
Fragmentation: the segment disease
Segmentation suffers from external fragmentation: as segments of varying sizes are allocated and freed, physical memory becomes a patchwork of free holes. A new segment may not fit into any single hole, even if the sum of free space is sufficient.
The solution — compaction (shuffling all allocated segments to one end of memory) — is expensive during execution-time binding (but feasible with an MMU: just update base registers, no need to copy data). At load-time binding, compaction requires relocating in-memory code and data, which is prohibitive.
External vs internal fragmentation
| Type | Cause | Example |
|---|---|---|
| External | Variable-sized allocations leave gaps between blocks | A 10 MB hole exists, but the new segment needs 12 MB; memory is free but unusable for this segment |
| Internal | Fixed-size allocation units waste space within allocated blocks | A segment of 6.2 KB is allocated an 8 KB chunk; 1.8 KB is wasted inside the segment |
Segmentation produces external fragmentation (variable segment sizes). Paging (next topic) produces only internal fragmentation (fixed page sizes).
Summary
- Segmentation divides memory into logical, variable-sized units matching programme structure.
- The segment table provides base, limit, and protection for each segment.
- Segments enable natural sharing and protection but suffer from external fragmentation.
- Compaction can fix fragmentation but is expensive; paging avoids the problem entirely.