Ref safety and stack allocation
Ref safety and stack allocation
Ref safety prevents references and ref-like values from escaping storage that cannot remain valid. A small stackalloc buffer is useful as synchronous scratch space, but it has method-local lifetime and limited capacity. For larger or variable work, a managed array or an explicitly leased pool buffer is often more suitable. Starting in C# 13, ref-like locals are permitted in certain async methods and iterators, provided they are not accessed across await or yield return. C# 14 retains this rule. Stackalloc storage without an initializer must be treated as uninitialized; fill or clear it before reading.
Baseline: .NET 10 / C# 14; inherited SDK candidate 10.0.404. Each example is an independent console project. Outputs are reasoned, not executed. The native-library example is Linux-only and requires the included C source.
Initialize bounded stack scratch space
Use a fixed small allocation outside a loop. Initialize every element before reading it; stackalloc contents are not guaranteed zero.
using System;Span<int> scratch = stackalloc int[3];scratch.Clear();scratch[1] = 8;Console.WriteLine(scratch[0] + scratch[1] + scratch[2]);Clear initializes the entire span. A stackalloc converted to Span<int> does not require an unsafe block under C# 14. Do not use an unbounded user-supplied size.
Expected observation (reasoned, not executed):
8Use a scoped parameter
The scoped modifier narrows ref escape possibilities. Return a scalar instead of a view into scratch memory.
using System;Span<int> values = stackalloc int[] { 4, 6, 8 };Console.WriteLine(Sum(values));static int Sum(scoped ReadOnlySpan<int> items){ int total = 0; foreach (int item in items) total += item; return total;}The function reads the region during the call. A scalar result does not carry an alias to the buffer. scoped is a compiler lifetime restriction, not a synchronization mechanism.
Expected observation (reasoned, not executed):
18Rent and return a buffer
A rental may be larger than requested and contain previous values. Restrict operations to the logical length, initialize that region, and return the array exactly once.
using System;using System.Buffers;var pool = ArrayPool<int>.Shared;int[] rented = pool.Rent(3);try{ Span<int> used = rented.AsSpan(0, 3); used.Fill(2); Console.WriteLine(used[0] + used[1] + used[2]);}finally{ pool.Return(rented, clearArray: true);}The finally block ends the lease even if processing fails. Never access the array or its views after return. clearArray requests clearing if retained for reuse; it is not a general secure-erasure guarantee.
Expected observation (reasoned, not executed):
6Common mistakes and design trade-offs
Invalid example (do not compile as a positive fixture): static Span<int> Bad() { Span<int> x = stackalloc int[2]; return x; }. Returning x would expose storage after the call ends. Do not repeatedly stackalloc in a loop; use a fixed buffer outside it. MemoryPool<T>.Rent returns an IMemoryOwner<T>; dispose the owner only after all consumers finish. A pool is not automatically faster for small workloads.
Apply the concept
Choose storage for a synchronous checksum over 16 bytes, a variable 1 MB scratch buffer, and a buffer used by an awaited writer. Specify initialization, cleanup and invalid escape cases.
Check your work: Use bounded stack scratch for 16 bytes if appropriate; managed or pooled storage for 1 MB; Memory<byte> backed by a valid owner for awaited work. Initialize used bytes, return/dispose once, and never return a stack-backed span from its method.
Continue with the next planned lesson in this track. For authoritative details, consult the linked source evidence and the reference drafts. All examples remain pending compiler and runtime verification.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Ref safety and stack allocation — knowledge check
Apply the lesson concepts to the following scenarios.
Why initialize stackalloc contents?
Why is returning a local stackalloc span invalid?
What does Rent(3) guarantee?
When should a rented array be returned?
What does scoped enforce here?