Pinned memory object (source code)

= Pinned memory object

A <pinned memory object> is a normally <movable memory object> whose address must remain unchanged during a specified operation. Pinning permits a <pointer> to remain usable when the code consuming it cannot participate in the runtime's relocation of references. The <pinning lifetime> is part of that guarantee: an address retained beyond the protected operation need not remain valid. Microsoft's language reference specifies that a `fixed` statement prevents relocation during its body and restricts the declared pointer to that statement.<Fixed statement in the C reference by Microsoft>[Opening definition; array-element and object-field guarantees]{ref}

For an original layout example, consider96 <bytes> with a pinned16-<byte> object at offsets $[32,48)$ and one other16-<byte> live object. The remaining64 <bytes> are free. Even if the other object can move anywhere, the pinned object divides the address range into regions of32 and48 <bytes>. A56-<byte> contiguous allocation cannot fit. Moving the other object into $[0,16)$ gives free intervals $[16,32)$ and $[48,96)$, whose largest size is48 <bytes>. If both live objects could move, placing them in $[0,32)$ would instead leave a64-<byte> interval. Pinning can therefore limit <memory compaction> despite ample total free capacity.

The numerical layout omits allocation headers and <memory alignment>; a real allocator must include them. Pinning an object's address also does not by itself specify how its <virtual memory> pages are backed. The garbage collector's object-relocation guarantee and an operating system's physical-page residency rules concern different layers. Likewise, a <pinned buffer> in a storage cache may mean protection from eviction rather than this object-relocation guarantee.

Once the protected operation is finished, releasing its pin can restore the runtime's freedom to move the object during a later collection. The program still has to obey the language's reference-lifetime rules: releasing a pin does not convert an old unmanaged address into a relocatable reference. The general <garbage collection> process must update references when it moves surviving objects.<Fundamentals of garbage collection by Microsoft>[“What happens during a garbage collection”, relocating and compacting phases]{ref}