Main Memory: Allocation, Linking & Segmentation

compaction

Picture a half-empty parking lot full of scattered single gaps. To make room for a bus you ask everyone to pull forward and park bumper-to-bumper, sweeping all the empty space into one big block at the back. Tedious, and everyone has to stop and move — but now the bus fits. Compaction is doing this to memory: shuffle all the in-use blocks to one end so the free holes merge into a single large hole.

Concretely, compaction attacks external fragmentation by relocating processes in physical memory until the allocated blocks are contiguous and all the free space is collected together. It can only work if relocation is dynamic — that is, if each process's addresses are translated through a base register or MMU at run time — because the OS changes each moved process's base register to its new location and the program keeps working unchanged. If addresses were bound at compile or load time, you could not move a process after the fact, so compaction would be impossible.

Why it matters: compaction is the textbook cure for external fragmentation under contiguous allocation, but it is expensive: copying large blocks of memory takes real time, during which the affected processes cannot run. There are many possible compaction layouts and choosing a cheap one is itself a problem. Because of the cost, real systems mostly avoid the need for compaction by using paging instead, which sidesteps external fragmentation in the first place.

Layout before: [P1][30 KB hole][P2][60 KB hole]. After compaction: [P1][P2][90 KB hole]. Now an 80 KB process fits, where before it could not — but the OS had to copy P2 and update its base register to do it.

Merge scattered holes into one big hole — at the cost of copying memory.

Compaction is only possible with dynamic (run-time) relocation; you cannot compact processes whose addresses were fixed at compile or load time. And it stalls the moved processes, which is why paging is usually preferred over compaction.

Also called
memory compactiondefragmentation記憶體緊縮