In C#, what does Span<byte> buffer = stackalloc byte[16]; allocate, and why does it compile without the unsafe keyword?
answer
- where the bytes live
- freed when the method returns
- the span carries its length
- pointer form needs a switch
basics
~20 sIt reserves 16 bytes in the current method's stack frame and wraps them in a bounds-checked Span<byte>. The block is discarded when the method returns, never touches the GC, and is safe code because the span knows its length.
solid answer
~40 s`stackalloc byte[16]` carves 16 bytes out of the running method's stack frame; there is no heap object, nothing for the GC to track and no way to free it early, because the block disappears when the method returns. Assigned to a `Span<byte>` (allowed since C# 7.2), it is ordinary safe code: the span records its length, every index is bounds-checked, and the compiler's ref-safety rules stop the span from outliving the method. Only the pointer form, `byte* p = stackalloc byte[16];`, needs an `unsafe` context (CS0214 otherwise) and a project built with `AllowUnsafeBlocks` (CS0227 otherwise). The element type must be unmanaged, and the language leaves the contents undefined, so write or `Clear()` the buffer before relying on it. Keep it small: stack space is limited.
code
csharp · 23 lines// No unsafe keyword and no AllowUnsafeBlocks: stackalloc into a Span<T> is safe code.
byte[] packet = [0x10, 0x20, 0x30, 0x40, 0x50];
Console.WriteLine(Checksum(packet));
static int Checksum(ReadOnlySpan<byte> data)
{
Span<byte> scratch = stackalloc byte[16]; // lives in this method's stack frame
scratch.Clear(); // contents are undefined until written
for (int i = 0; i < data.Length; i++)
scratch[i % scratch.Length] ^= data[i];
int sum = 0;
foreach (byte b in scratch) sum += b;
try
{
scratch[16] = 1; // still bounds-checked
}
catch (IndexOutOfRangeException)
{
Console.WriteLine("index 16 rejected");
}
return sum;
}go deeper
Say where the bytes live, that the span form is safe code since C# 7.2, and that only the pointer form needs unsafe plus AllowUnsafeBlocks.
Explain the two gates (CS0214 for the unsafe context, CS0227 for the project switch), the unmanaged element rule and why contents are undefined.
Show the production pattern: a small constant-size block sliced to the real length, a heap or pooled fallback above it, and no stackalloc sized from input.
Treat stackalloc into spans as the allowed, reviewable way to avoid small allocations, keeping the pointer form inside the code the team has agreed may be unsafe.
## What the line allocates `stackalloc` is a C# expression that reserves a block of memory **on the stack of the current thread, inside the frame of the method that runs it**. In ```csharp Span<byte> buffer = stackalloc byte[16]; ``` the runtime reserves 16 bytes (possibly rounded up for alignment) and `buffer` becomes a `Span<byte>` whose reference points at the first byte and whose `Length` is 16. Three properties follow from where the memory lives: - **No heap allocation.** There is no `byte[]` object, so nothing is added to the managed heap and the garbage collector never sees the block. - **No explicit free.** You cannot release it early. The block is discarded when the method returns, together with the rest of the frame. - **No pinning.** Stack memory never moves, so it can be handed to pointer code without a `fixed` statement. ## Why the span form is safe code Before C# 7.2, `stackalloc` produced only a pointer, so it was an unsafe feature. C# 7.2 added `Span<T>` and `ReadOnlySpan<T>` as targets, and that form needs no `unsafe` keyword and no compiler switch, because: 1. **The span carries its length.** `buffer[16]` on a 16-byte span throws `IndexOutOfRangeException`; it cannot read the bytes next to the block. 2. **The compiler limits its lifetime.** `Span<T>` is a ref struct, and the ref-safety rules reject code that would let a stackalloc'd span escape the method; returning it fails with CS8352. The full escape rules belong to the lesson on ref structs and lifetimes. 3. **Nothing is reinterpreted.** You index `byte` values through the span's API; there is no pointer arithmetic to get wrong. Later releases only widened the syntax: C# 7.3 added initializers (`stackalloc byte[] { 1, 2, 3 }`) and C# 8 allowed `stackalloc` nested inside other expressions, such as one arm of a conditional. ## The pointer form and the compiler switch The same expression can still initialise a pointer local, and that form is unsafe in the original sense: | Form | `unsafe` context | `AllowUnsafeBlocks` | Bounds-checked | |---|---|---|---| | `Span<byte> b = stackalloc byte[16];` | not needed | not needed | yes | | `ReadOnlySpan<int> r = stackalloc int[] { 1, 2 };` | not needed | not needed | yes | | `byte* p = stackalloc byte[16];` | required (CS0214) | required (CS0227) | no | Two separate gates guard the pointer form. Writing a pointer outside an `unsafe` block or member fails with CS0214, *Pointers and fixed size buffers may only be used in an unsafe context*. Writing an `unsafe` block in a project without `<AllowUnsafeBlocks>true</AllowUnsafeBlocks>` fails with CS0227, *Unsafe code may only appear if compiling with /unsafe*. The switch is off by default, so a team sees unsafe code arrive in the project file. A pointer `stackalloc` is also allowed only as the initializer of a local declaration. ## Rules on what can be stack-allocated - **The element type must be unmanaged**: primitives, enums, pointers and structs with no reference fields. `stackalloc string[4]` fails with CS0208, because the GC would not track object references stored in such a block. - **The length must be a non-negative `int`.** It may be computed at run time, which is exactly where the risk of running out of stack comes from. - **The contents are undefined.** The language reference says so and tells you to initialise the block. In practice the C# compiler marks methods with the `.locals init` flag, so the runtime zeroes the block; applying `[SkipLocalsInit]` (which itself requires `AllowUnsafeBlocks`) removes that and leaves whatever bytes were on the stack. Code that reads before writing should call `Clear()` or use an initializer. - **The stack is small and fixed per thread.** Its size depends on the operating system and how the thread was created, so a large or input-sized `stackalloc` can overflow it and terminate the process. ## When to reach for it `stackalloc` into a span suits **small, short-lived scratch buffers on hot paths**: formatting a number into characters, decoding a fixed-size header, collecting a handful of indices. The usual pattern is a constant-size block (a few hundred bytes), sliced to the length actually needed, with a heap or pooled array when the input is larger. For anything that must outlive the call, cross an `await` or grow without bound, use an array or a pooled buffer instead.
- Can a C# method return the Span<byte> it got from stackalloc?No. The block is part of the method's frame and disappears on return, so the compiler's ref-safety analysis rejects `return buffer;` with CS8352 (the variable may expose referenced variables outside their declaration scope). Return a value computed from the buffer, write into a span the caller passes in, or allocate an array when the data must outlive the call.
- Is stackalloc memory zeroed in C#?The language does not promise it: the reference says the contents are undefined. By default the compiler emits `.locals init`, so the runtime zeroes the block anyway. `[SkipLocalsInit]`, which needs `AllowUnsafeBlocks`, drops that flag and saves the zeroing cost, and then the block holds leftover stack bytes. Code that reads before writing should call `Clear()` or use an initializer.
- Why does stackalloc string[4] not compile in C#?`stackalloc` accepts only unmanaged element types. A `string` element is an object reference, which the GC would not track inside a stack-allocated block, so the compiler reports CS0208 (cannot declare a pointer to a managed type). Use a `string[]`, or an `[InlineArray]` struct if you need a fixed number of references stored inline.
- stackalloc always needs an unsafe block and the AllowUnsafeBlocks switch
- stackalloc memory is freed by the GC like any other buffer
- A Span over stackalloc memory skips bounds checks
- stackalloc memory is guaranteed zeroed, exactly like new byte[n]
- Any input size is fine because the stack grows as needed