Interview frequency: …
Short answer
Pinning prevents the GC from moving an object at a specific RAM address while passing it to unmanaged (C/C++) code; it can hinder memory compaction and cause severe Heap fragmentation.
Explanation
The GC normally compacts memory and moves objects to create contiguous free space. If calling a native C function through P/Invoke that expects a fixed address, fixed pins the object and prevents the GC from moving it while the block runs. Excessive pinning of Gen 0/1 objects interferes with GC compaction and creates memory fragmentation.
Code example
unsafe {
byte[] buffer = new byte[100];
fixed (byte* p = buffer) {
// The pointer p is fixed here and cannot be moved by the GC
NativeMethods.FillBuffer(p, 100);
}
}Common mistakes
- Pinning objects for very long periods, preventing Heap compaction and causing Memory Fragmentation.
Follow-up questions
- How does the .NET Garbage Collector work, and what are the three generations (Gen 0, Gen 1, Gen 2)?
- What is the Large Object Heap (LOH) in .NET, and why is it prone to Memory Fragmentation?