Memory Fragmentation and Compaction
Memory that is free or allocated but cannot be used. Internal fragmentation is lost inside blocks, external fragmentation is lost between them, and compaction moves blocks to merge the gaps.
Two Kinds of Fragmentation in OS
Memory fragmentation in an operating system is memory that exists but cannot be used for the request at hand. It comes in two kinds with different causes and different cures.
Internal fragmentation is space lost inside a block a process was given: the allocator rounded the request up to a partition, page or size class, and the extra is held but unused. External fragmentation is free memory lost between blocks: there is enough in total, but it is split into holes and no single hole is big enough.
- Internal: allocated but unused
- External: free but in pieces too small
Difference Between Internal and External Fragmentation
The difference between internal and external fragmentation comes down to where the waste sits and what causes it. Internal fragmentation comes from fixed-size units, external fragmentation from variable-size blocks, so an allocator chooses which one it is willing to pay.
| Internal | External | |
|---|---|---|
| Where the waste is | Inside an allocated block | Between allocated blocks |
| Cause | Rounding a request up to a fixed unit | Variable-sized blocks allocated and freed |
| Counted as | Used memory | Free memory |
| Size | Under one unit per allocation | Grows with churn; about N/2 holes for N blocks |
| Typical schemes | Fixed partitions, paging, buddy system | Variable partitions, segmentation, heaps |
| Remedy | Smaller units or closer size classes | Compaction, or paging |
- Fixed units trade external fragmentation for internal
- Exact sizes trade internal fragmentation for external
Why Paging Accepts Internal Fragmentation
Paging makes every unit the same size. Any free frame can hold any page, so a request for k pages needs any k free frames, wherever they are, and there is no such thing as a hole too small. External fragmentation of physical memory disappears.
The price is internal fragmentation in the last page of each allocation: at most one page, about half a page on average. With 4 KB pages that is about 2 KB per allocation, small next to processes that use megabytes. With 2 MB huge pages the average loss is about 1 MB, which is why huge pages are kept for large mappings.
- One unit size: every free frame fits every page
- Cost: up to one page per allocation
Compaction, move by move
SIZE = 76
BLOCKS = {"A": (0, 12), "E": (24, 5), "H": (53, 20)}
REQUEST = 26
def holes(blocks):
out, pos = [], 0
for start, size in sorted(blocks.values()):
if start > pos:
out.append(start - pos)
pos = start + size
if SIZE > pos:
out.append(SIZE - pos)
return out
def full_compaction(blocks):
moved, pos, out = 0, 0, {}
for name, (start, size) in sorted(blocks.items(), key=lambda b: b[1][0]):
if start != pos:
moved += size
out[name] = (pos, size)
pos += size
return out, moved
def cheapest_single_move(blocks, request, pinned=()):
best = None
for name, (start, size) in blocks.items():
if name in pinned:
continue
others = {n: b for n, b in blocks.items() if n != name}
spots = [0] + [s + z for s, z in others.values()]
for spot in spots:
end = spot + size
if end > SIZE or any(spot < s + z and s < end for s, z in others.values()):
continue
trial = dict(others, **{name: (spot, size)})
if max(holes(trial)) >= request and (best is None or size < best[2]):
best = (name, spot, size)
return best
h = holes(BLOCKS)
print(f"holes {h}: {sum(h)} KB free, largest {max(h)} KB, request {REQUEST} KB fails")
after, moved = full_compaction(BLOCKS)
print(f"full compaction: copied {moved} KB, largest hole {max(holes(after))} KB")
name, spot, size = cheapest_single_move(BLOCKS, REQUEST)
print(f"cheapest: move {name} to {spot}, copied {size} KB")
name, spot, size = cheapest_single_move(BLOCKS, REQUEST, pinned=("E",))
print(f"E pinned: move {name} to {spot}, copied {size} KB")#include <algorithm>
#include <cstdio>
#include <map>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
using namespace std;
const int SIZE = 76;
using Blocks = map<string, pair<int, int>>; // name -> (start, size)
vector<int> holes(const Blocks& blocks) {
vector<pair<int, int>> v;
for (auto& [n, b] : blocks) v.push_back(b);
sort(v.begin(), v.end());
vector<int> out;
int pos = 0;
for (auto [start, size] : v) {
if (start > pos) out.push_back(start - pos);
pos = start + size;
}
if (SIZE > pos) out.push_back(SIZE - pos);
return out;
}
int largest(const Blocks& b) { auto h = holes(b); return *max_element(h.begin(), h.end()); }
pair<Blocks, int> fullCompaction(const Blocks& blocks) {
vector<pair<int, string>> order;
for (auto& [n, b] : blocks) order.push_back({b.first, n});
sort(order.begin(), order.end());
Blocks out;
int moved = 0, pos = 0;
for (auto& [start, n] : order) {
int size = blocks.at(n).second;
if (start != pos) moved += size;
out[n] = {pos, size};
pos += size;
}
return {out, moved};
}
// returns (name, spot, size); name empty if none
tuple<string, int, int> cheapestSingleMove(const Blocks& blocks, int request, const string& pinned) {
tuple<string, int, int> best = {"", 0, 0};
for (auto& [name, b] : blocks) {
if (name == pinned) continue;
int size = b.second;
Blocks others = blocks;
others.erase(name);
vector<int> spots = {0};
for (auto& [n, o] : others) spots.push_back(o.first + o.second);
for (int spot : spots) {
int end = spot + size;
bool clash = end > SIZE;
for (auto& [n, o] : others) if (spot < o.first + o.second && o.first < end) clash = true;
if (clash) continue;
Blocks trial = others;
trial[name] = {spot, size};
if (largest(trial) >= request && (get<0>(best).empty() || size < get<2>(best)))
best = {name, spot, size};
}
}
return best;
}
int main() {
Blocks blocks = {{"A", {0, 12}}, {"E", {24, 5}}, {"H", {53, 20}}};
int request = 26;
auto h = holes(blocks);
int total = 0;
for (int x : h) total += x;
printf("holes [%d, %d, %d]: %d KB free, largest %d KB, request %d KB fails\n", h[0], h[1], h[2], total, largest(blocks), request);
auto [after, moved] = fullCompaction(blocks);
printf("full compaction: copied %d KB, largest hole %d KB\n", moved, largest(after));
auto [n1, s1, z1] = cheapestSingleMove(blocks, request, "");
printf("cheapest: move %s to %d, copied %d KB\n", n1.c_str(), s1, z1);
auto [n2, s2, z2] = cheapestSingleMove(blocks, request, "E");
printf("E pinned: move %s to %d, copied %d KB\n", n2.c_str(), s2, z2);
}import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class Main {
static final int SIZE = 76;
static List<Integer> holes(Map<String, int[]> blocks) {
List<int[]> v = new ArrayList<>(blocks.values());
v.sort((a, b) -> a[0] - b[0]);
List<Integer> out = new ArrayList<>();
int pos = 0;
for (int[] b : v) {
if (b[0] > pos) out.add(b[0] - pos);
pos = b[0] + b[1];
}
if (SIZE > pos) out.add(SIZE - pos);
return out;
}
static int largest(Map<String, int[]> b) {
int m = 0;
for (int x : holes(b)) m = Math.max(m, x);
return m;
}
static int fullCompaction(Map<String, int[]> blocks, Map<String, int[]> out) {
List<Map.Entry<String, int[]>> order = new ArrayList<>(blocks.entrySet());
order.sort((a, b) -> a.getValue()[0] - b.getValue()[0]);
int moved = 0, pos = 0;
for (Map.Entry<String, int[]> e : order) {
int size = e.getValue()[1];
if (e.getValue()[0] != pos) moved += size;
out.put(e.getKey(), new int[]{pos, size});
pos += size;
}
return moved;
}
// returns {name, spot, size} or null
static Object[] cheapestSingleMove(Map<String, int[]> blocks, int request, String pinned) {
Object[] best = null;
for (Map.Entry<String, int[]> e : blocks.entrySet()) {
String name = e.getKey();
if (name.equals(pinned)) continue;
int size = e.getValue()[1];
Map<String, int[]> others = new TreeMap<>(blocks);
others.remove(name);
List<Integer> spots = new ArrayList<>(List.of(0));
for (int[] o : others.values()) spots.add(o[0] + o[1]);
for (int spot : spots) {
int end = spot + size;
boolean clash = end > SIZE;
for (int[] o : others.values()) if (spot < o[0] + o[1] && o[0] < end) clash = true;
if (clash) continue;
Map<String, int[]> trial = new TreeMap<>(others);
trial.put(name, new int[]{spot, size});
if (largest(trial) >= request && (best == null || size < (int) best[2]))
best = new Object[]{name, spot, size};
}
}
return best;
}
public static void main(String[] args) {
Map<String, int[]> blocks = new TreeMap<>();
blocks.put("A", new int[]{0, 12});
blocks.put("E", new int[]{24, 5});
blocks.put("H", new int[]{53, 20});
int request = 26;
List<Integer> h = holes(blocks);
int total = 0;
for (int x : h) total += x;
System.out.println("holes " + h + ": " + total + " KB free, largest " + largest(blocks) + " KB, request " + request + " KB fails");
Map<String, int[]> after = new TreeMap<>();
int moved = fullCompaction(blocks, after);
System.out.println("full compaction: copied " + moved + " KB, largest hole " + largest(after) + " KB");
Object[] a = cheapestSingleMove(blocks, request, "");
System.out.println("cheapest: move " + a[0] + " to " + a[1] + ", copied " + a[2] + " KB");
Object[] b = cheapestSingleMove(blocks, request, "E");
System.out.println("E pinned: move " + b[0] + " to " + b[1] + ", copied " + b[2] + " KB");
}
}Step through it
Running on 76 KB region: A 12 | 12 free | E 5 | 24 free | H 20 | 3 free · request 26 KB
How Compaction Works
- Pick the blocks to move, fewest bytes first
- Copy each block to its new place while its process is paused
- Update its base register or page table entries
- Merge the holes that now touch into one
Memory compaction moves allocated blocks so that free holes become one contiguous run. Take a 76 KB region holding A (12 KB), a 12 KB hole, E (5 KB), a 24 KB hole, H (20 KB) and a 3 KB hole. 39 KB is free, but a 26 KB request fails because the largest hole is 24 KB.
Full compaction slides E from 24 to 12 and H from 53 to 17, leaving one 39 KB hole and copying 25 KB. Moving only E to 12 joins the 12 and 24 KB holes into 36 KB, enough for 26, and copies 5 KB. Compaction never adds memory; it changes the shape of what is free, and good compactors choose the fewest bytes to move.
- Full compaction here: 25 KB copied
- Moving only E: 5 KB copied
When Compaction Is Possible
Compaction needs dynamic relocation: addresses must be translated at run time, by a base register or a page table, so the OS can move a block and change only the mapping. If a program's addresses were fixed at compile or load time, moving it leaves the program using old physical addresses, and it corrupts whatever lands there next. In that case compaction cannot be done at all.
Some blocks cannot move even with relocation. A buffer that a device is filling by DMA is pinned to its physical address until the transfer ends. If E were pinned, the cheapest plan would move H from 53 to 29 instead, merging the 24 KB hole with the 3 KB tail into 27 KB at a cost of 20 KB copied.
- Run-time relocation required
- Pinned blocks must stay put
Where Compaction Is Used Today
Linux compacts physical memory on demand, through direct compaction and the kcompactd thread, to assemble free 2 MB runs for huge pages and contiguous buffers; the free-block counts in /proc/buddyinfo show how fragmented each zone is. Garbage-collected runtimes such as the JVM and .NET compact the heap during collection, since the collector already finds and updates every reference.
Allocators that cannot move objects, such as malloc, rely on prevention instead: the buddy system merges a freed block with its buddy in O(1), slab caches keep same-sized objects together, and size classes limit how much is lost to rounding. Where blocks are placed is covered in memory allocation algorithms.
- Linux: on demand, for huge pages
- Garbage collectors: during collection
- malloc: cannot move objects, so it prevents instead