Memory in Logical Units
While paging divides memory into fixed-size blocks, segmentation divides it into variable-size blocks based on logical units. Think of it like a book — it's divided into chapters, each with a different length. You don't force every chapter to be exactly 10 pages; each chapter is as long as it needs to be.
In segmentation, a program is divided into segments based on its structure: the code segment, the data segment, the stack segment, and so on. Each segment has a name and a length, and the programmer (or compiler) is often aware of these segments.
How Segmentation Works
Each segment represents a logical unit of the program:
- Code Segment — Contains the program's instructions. Typically read-only.
- Data Segment — Contains global variables and constants.
- Stack Segment — Contains local variables, function parameters, and return addresses. Grows and shrinks dynamically.
- Heap Segment — Contains dynamically allocated memory (like when you use
mallocin C).
A segment table maps each segment to its base address (where it starts in physical memory) and its limit (how long it is). When a process accesses memory, the CPU uses the segment table to translate the logical address to a physical address.
Segmentation vs. Paging
- Paging is invisible to the programmer — the hardware handles everything. Memory is divided into arbitrary fixed-size blocks.
- Segmentation is visible to the programmer — segments correspond to meaningful parts of the program. Memory is divided into variable-size blocks based on logical structure.
The advantage of segmentation is that it matches how programmers think about memory. The code, data, and stack are logically separate things, and segmentation preserves that distinction.
The disadvantage is external fragmentation — just like contiguous allocation, variable-sized segments leave gaps in memory. Over time, these gaps add up and make it hard to find space for new segments.
Segmentation with Paging
Many modern systems combine both approaches. Intel x86-64 architecture uses segmentation for some purposes and paging for address translation. The segmentation hardware divides memory into segments, and then paging subdivides each segment into pages.
This hybrid approach gets the logical clarity of segmentation with the efficient memory allocation of paging. It's more complex, but it provides the best of both worlds.