In C# unsafe code, why must a byte* into a managed byte[] come from a fixed statement, and what does pinning cost?
answer
- the GC compacts the heap
- raw pointers are not tracked
- pinned only inside the braces
- pins block compaction
basics
~20 sThe GC can move a byte[] while compacting and never updates raw pointers. fixed pins the array for the statement's body so the pointer stays valid; the cost is an immovable object, which hinders compaction when pins are long or many.
solid answer
~40 sA `byte[]` lives on the managed heap, and the garbage collector may move it to compact memory. It updates references and `ref`s, but it does not know about a raw `byte*`, so a pointer taken without protection could end up pointing at whatever moved into the old address. C# therefore rejects `&rgba[0]` outside a `fixed` initializer with CS0212. `fixed (byte* p = rgba) { ... }` pins the array for the body of the statement: the pointer is read-only, valid only inside the braces, and the pin is released at the closing brace. Pinning has a cost: while pinned the object cannot move, so many or long-lived pins fragment the heap. Keep pins short, guard lengths before the loop, because pointer access is not bounds-checked, and remember that stack memory needs no pin.
code
csharp · 17 lines#:property AllowUnsafeBlocks=true
byte[] rgba = [255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255];
byte[] luma = new byte[rgba.Length / 4];
ToGray(rgba, luma);
Console.WriteLine(string.Join(", ", luma));
static unsafe void ToGray(byte[] rgba, byte[] luma)
{
if (rgba.Length < luma.Length * 4) throw new ArgumentException("rgba too short");
fixed (byte* src = rgba) // pins rgba until the closing brace
fixed (byte* dst = luma) // pins luma too
{
byte* p = src;
for (int x = 0; x < luma.Length; x++, p += 4) // no bounds checks from here on
dst[x] = (byte)((p[0] * 77 + p[1] * 150 + p[2] * 29) >> 8);
}
}go deeper
Recall that the GC moves heap objects, so a pointer into an array is only safe inside a fixed statement, and that unsafe code needs AllowUnsafeBlocks.
Explain fixed versus moveable variables, CS0212, the read-only pointer scoped to the block, and the null pointer for an empty array.
Keep pins short, validate lengths before unchecked pointer loops, and know when span indexing or a pinned allocation is the better tool.
Weigh pinning's fragmentation cost and unchecked memory access against the measured gain before allowing pointer code on a hot path.
## Why a raw pointer into an array needs protection Arrays, strings and class instances live on the **managed heap**, and .NET's garbage collector is a **compacting** collector: to remove gaps left by dead objects it can move live objects to new addresses. When it does, it updates every reference and every managed `ref` that points into the moved object. A C# pointer (`byte*`) is not one of those. It is a plain address that the GC neither reports nor rewrites. If you could take `&rgba[0]` freely, a collection between two reads could move `rgba`, and the pointer would silently point at stale memory or at a different object. So the compiler distinguishes: - **Fixed variables**: locals, value parameters and stack-allocated memory, which never move. You can take their address directly, and trying to `fix` them fails with CS0213. - **Moveable variables**: array elements, fields of class instances, string characters. Their address may be taken **only** in a `fixed` statement initializer; anywhere else the compiler reports CS0212, *You can only take the address of an unfixed expression inside of a fixed statement initializer*. ## What the fixed statement does ```csharp fixed (byte* src = rgba) { // src stays valid here } ``` 1. The compiler stores a reference to the array in a **pinned local**, which tells the GC that this object must not move while the local is live. 2. It computes the address of the first element and assigns it to `src`, which is **read-only**: you cannot reassign it, but you can copy it to another pointer and increment that. 3. At the closing brace the pinned local is cleared and the object may move again. A pointer copied out of the block is not protected after that point. If the array is `null` or empty, the initializer produces a **null pointer**, so a pointer loop must still check the length first. Several declarations can be stacked (`fixed (byte* src = rgba) fixed (byte* dst = luma) { ... }`) to pin two arrays at once. ## What can be fixed | Initializer | What gets pinned | Pointer points at | |---|---|---| | `byte[]` | the array | element 0, or null if empty or null | | `string` | the string | the first `char` | | `&obj.Field` | the containing object | the field | | `Span<T>` / `ReadOnlySpan<T>` | the memory behind the span, via `GetPinnableReference` | element 0 | | fixed-size buffer field | the containing object | element 0 | Pinning a string gives a `char*` over memory that every other piece of code assumes is immutable; writing through it compiles, but it breaks that assumption and is a bug. ## What pinning costs - **Fragmentation.** A pinned object is a rock in the middle of the heap: the GC must compact around it. A short pin in a tight loop is cheap; thousands of concurrent pins or pins held across slow I/O leave gaps the allocator cannot use. The heap mechanics, including the pinned object heap that `GC.AllocateArray<T>(length, pinned: true)` allocates on for buffers that stay pinned for their whole life, belong to the material on the managed heap. - **No bounds checks.** Inside the block, `src[i]` and `*p` are raw memory accesses. Reading past the end returns neighbouring bytes and writing past it corrupts them, so validate every length **before** the loop. - **Unsafe code.** `fixed` requires an `unsafe` context and `AllowUnsafeBlocks`. ## When you do not need it Many loops that reach for `fixed` are just as well served by **span indexing**: the JIT removes bounds checks when it can prove the index is in range, and `Span<T>` gives the same element access without a pin. Memory from `stackalloc` is already on the stack and never moves. If a pointer is needed over memory a span already describes, pin the span itself: `fixed (byte* p = span)` works through `Span<T>.GetPinnableReference`, so the same pointer code accepts arrays, stack memory and native memory alike. `fixed` earns its place when the code genuinely needs a pointer: pointer arithmetic over interleaved channels (four bytes per RGBA pixel), handing an address to code that takes one, or a measured hot loop where bounds checks did not disappear.
- In C#, does a pointer to a local int or to stackalloc memory need a fixed statement?No. Locals, value parameters and stack-allocated memory are fixed variables: the GC never moves them, so `int* q = &local;` is legal inside an unsafe context. Writing `fixed (int* p = &local)` is an error, CS0213 (cannot fix an already fixed expression). Only moveable variables such as array elements, class fields and string characters need `fixed`.
- What does a fixed statement give you for an empty or null byte[] in C#?A null pointer. The language defines the initializer's result as zero when the array is null or has no elements, so a loop that dereferences the pointer without checking the length first will dereference null. Check `Length` before entering the pointer code, or handle the empty case separately.
- When would you allocate a buffer with GC.AllocateArray<T>(length, pinned: true) instead of using fixed?When a buffer must stay at one address for a long time, for example handed to code that keeps its address across many calls. Repeated or long `fixed` pins on ordinary heap arrays hinder compaction; an array allocated pinned is placed on the pinned object heap from the start. The heap details belong to the material on the garbage collector.
- A pointer to a managed array stays valid because the GC never moves arrays
- The pointer from fixed remains safe to use after the closing brace
- Pointer indexing inside fixed is still bounds-checked like array indexing
- Pinning is free, so a buffer can stay pinned across slow I/O
- stackalloc memory has to be pinned with fixed before taking its address