`stackalloc` Buffer Allocation & Stack Overflow Protection
1Concept
`stackalloc` allocates memory directly on the thread stack frame. Stack memory is automatically reclaimed when the function returns without triggering GC collections.
2Architecture Diagram
stackalloc Span<byte> (Thread Stack Frame): ┌─────────────────────────┬─────────────────────────┬─────────────────────────┐ │ Byte 0 │ Byte 1 │ Byte 2 ... 127 │ └─────────────────────────┴─────────────────────────┴─────────────────────────┘ ▲ Allocated in 1 CPU instruction (`sub rsp, size`); deallocated on RET (Zero GC!)
3Code Example
C# 13 & .NET 9
using System;
public class StackAllocDemo
{
public static void FormatHeader(int id)
{
// Stack allocated temporary buffer (Zero GC pressure)
Span<char> buffer = stackalloc char[32];
bool success = id.TryFormat(buffer, out int charsWritten, "X8");
Console.WriteLine($"Formatted Hex ID: {buffer.Slice(0, charsWritten).ToString()}");
}
public static void Main()
{
FormatHeader(0x00FF_EEDD);
}
}4Expected Output
Formatted Hex ID: 00FFEEDD
5Key Takeaways
- ✓Use `stackalloc` only for small buffers (< 1024 bytes) to prevent StackOverflowException.
- ✓For dynamic buffer sizes, check `size <= 512 ? stackalloc byte[size] : new byte[size]`.
- ✓Always assign `stackalloc` to a `Span<T>` for bounds safety.