Senior · Explain · Pinned lifetimes and the pinned-object heap

How do pinning an existing array and allocating a pinned array differ?

Think through your answer before opening the explanation.

Memory & GC

Reveal answer and reasoning

Pinning an already allocated array does not migrate it to the pinned-object heap. Moving an object simply because the caller wants its current address fixed would itself require coordination and movement, undermining the operation's purpose. CoreCLR instead exposes allocation-time pinning APIs for suitable scenarios. An array allocated pinned can be placed in POH from its creation rather than moving an existing object there later.

POH still participates in managed lifetime management. An allocation-pinned array is not immortal, and retaining a pin is not equivalent to leaking a native allocation forever. A normal managed owner can keep it live; when the required strong ownership ends, a collection including the appropriate heap can reclaim it. POH avoids mixing those deliberately pinned allocations with ordinary movable storage, but it does not remove allocation cost, fragmentation concerns or the need for a bounded pool.

A native asynchronous API can return before it finishes using a buffer. Releasing the pin immediately after submission can therefore be incorrect even if the buffer remains strongly reachable. The native consumer needs both valid lifetime and stable address until its completion or acknowledged cancellation boundary. A cancellation request alone may not establish that the native side has stopped accessing memory.

Design one owner for the handle and one explicit terminal path. Success, failure during submission, cancellation before submission and cancellation after acceptance can have different obligations. Free the handle exactly once after the consumer is finished. Avoid copying ownership-bearing handle structs casually: two copies that both believe they own a release can create a double-free bug. SafeHandle and purpose-built wrappers can encode resource-specific release policy, but they still need a correct completion contract.

What a strong answer covers

  • Pinning an existing object does not migrate it to POH.
  • A pointer lease must end after native consumption, not merely after submission.
  • POH objects remain collectible when no strong owner remains.

Common pitfall

Claiming that pinning an existing array moves it to POH, or freeing a pin before asynchronous native consumption ends.

Follow-up questions

  1. What acknowledgement permits releasing a pin after cancellation?
  2. Can generation2 alone distinguish POH from other storage?

Self-review

Choose what to revisit. These marks are your own assessment and are separate from lesson completion.

Primary references

Open lesson and code ↗

← All interview questions