liveBook · Manning

Heap fragmentation

As explained in .NET in Action, Second Edition

Heap fragmentation is a memory-allocation condition in which free heap space is divided into separated regions that may not provide a sufficiently large contiguous block.

Heap fragmentation occurs when free space is split into separate gaps. An array needs one contiguous chunk, so enough free space in total does not guarantee room for a new allocation. section 10.3.4

A fragmented 1 MB heap

Imagine a 1 MB heap filled with allocated chunks. Collection frees unused chunks, but the gaps remain too small for the next allocation. If the heap cannot grow, compaction moves the remaining chunks together to make contiguous space. section 10.3.4

Moving arrays matters when code uses pointers to them. In an unsafe C# copy routine, fixed keeps the source and target arrays in place until the pointer-based copy finishes. section 10.3.4

Figure 10.9 The heap after compaction

The heap after compaction shows why moving allocated chunks can resolve a fragmented layout. section 10.3.4

How .NET in Action, Second Edition covers it

How deep it goes
Works through allocation, collection, and compaction with a 1 MB heap scenario.
Examples
Uses heap-layout figures and an unsafe C# array-copy listing.
What it assumes
Assumes familiarity with C# arrays while introducing collection and compaction through a concrete heap scenario.
What you can do after
Evaluate/understand why total free space may not fit an allocation and why pointer-accessed arrays must remain in place.
How it connects
Connects heap fragmentation to garbage collection, compaction, contiguous allocation, pointers, and C# fixed blocks.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.