A C# grayscale converter calls stackalloc inside its per-row loop and crashes with 'Stack overflow.' on large frames; why, and how do you size the buffer safely?
answer
- freed only at method return
- blocks pile up per iteration
- the analyzer flags this one
- constant cap, heap fallback
basics
~20 sEach stackalloc in the loop takes a new block that is released only when the method returns, so per-row buffers pile up until the stack runs out. Allocate one capped buffer before the loop and fall back to the heap.
solid answer
~40 s`stackalloc` memory belongs to the method's frame and is released only when the method returns, so a `stackalloc byte[width]` inside a row loop reserves a fresh block on every iteration: rows times width bytes, all still live. On a wide, tall frame that exceeds the thread's stack, and a stack overflow is not a catchable exception: the runtime prints `Stack overflow.` and terminates the process, skipping every `catch` and `finally`. The .NET 10 SDK flags this pattern by default with CA2014 (*Potential stack overflow. Move the stackalloc out of the loop.*). The fix is to allocate once, before the loop, with a constant-size `stackalloc` below a conservative threshold (a few hundred bytes to about 1 KB), slice it to the real length, and use a heap array or a pooled one above that threshold.
code
csharp · 20 lines// Grayscale conversion: one RGBA row at a time into a luma row.
const int Width = 64, Height = 4;
byte[] frame = new byte[Width * Height * 4];
for (int i = 0; i < frame.Length; i++) frame[i] = (byte)(i * 7);
for (int y = 0; y < Height; y++)
{
Span<byte> luma = stackalloc byte[Width]; // CA2014: a new block every iteration
ToGray(frame.AsSpan(y * Width * 4, Width * 4), luma);
}
Console.WriteLine("done");
static void ToGray(ReadOnlySpan<byte> rgba, Span<byte> luma)
{
for (int x = 0; x < luma.Length; x++)
{
int r = rgba[x * 4], g = rgba[x * 4 + 1], b = rgba[x * 4 + 2];
luma[x] = (byte)((r * 77 + g * 150 + b * 29) >> 8);
}
}go deeper
Recall that stackalloc memory lives until the method returns and that the stack is small, so a stackalloc in a loop keeps reserving more.
Explain why the blocks accumulate, what CA2014 reports, and how a constant-size block sliced to the real length keeps stack use fixed.
Diagnose the crash from the 'Stack overflow.' output, explain why nothing caught it, and ship the capped-stackalloc-with-fallback fix plus a test at production frame sizes.
Make an input-independent bound on every stackalloc a review rule, keep CA2014 at warning or error, and require large-input tests on hot paths.
## Why the loop exhausts the stack A grayscale converter typically walks a frame of RGBA pixels row by row and writes one luma byte per pixel into a scratch row. Written naively: ```csharp for (int y = 0; y < height; y++) { Span<byte> luma = stackalloc byte[width]; // a new block every iteration ToGray(frame.AsSpan(y * width * 4, width * 4), luma); } ``` The key rule is **when stack-allocated memory is released**: the language reference says a `stackalloc` block is discarded when the *method* returns, and you cannot free it explicitly. Leaving a loop body does not release anything. So: - each iteration moves the stack pointer down by `width` more bytes; - after `height` iterations the frame holds `width * height` bytes of dead scratch rows; - a 3840 x 2160 frame asks for more than 8 MB of stack. Small test images pass; production frames crash. The bug survives review because the line looks local and tidy: the buffer is declared where it is used, exactly as a `new byte[width]` would be, and the span is bounds-checked, so nothing looks unsafe. The size is also **driven by input**, so the same code is a denial-of-service risk when the width comes from a file header or a request. ## What the failure looks like When a thread runs off its stack, .NET does not deliver a catchable exception. The runtime treats a `StackOverflowException` as fatal: it prints `Stack overflow.` with the managed frames that were on the stack and terminates the process. A `catch (Exception)` around the call never runs, and neither do `finally` blocks or `using` cleanup. That is why the rule is to **prevent** the overflow rather than handle it. ## The fix: one buffer, allocated once 1. **Move the `stackalloc` out of the loop.** One block per call, reused for every row, is exactly what the documentation and CA2014 prescribe. 2. **Allocate a constant size and slice it.** `stackalloc byte[MaxStackBytes]` followed by `luma = luma[..width]` keeps the stack cost fixed whatever the input says. 3. **Fall back to the heap above the threshold.** A conditional expression can pick between `stackalloc` and `new byte[width]` (allowed since C# 8, which permits `stackalloc` nested in expressions), or rent from `ArrayPool<byte>.Shared` and return the array in a `finally`; the rent/return rules belong to the lesson on pooled buffers. 4. **Keep the rest of the code span-based.** `ToGray(ReadOnlySpan<byte>, Span<byte>)` neither knows nor cares where its buffer lives. | Approach | Stack cost per call | Heap allocation | Risk | |---|---|---|---| | `stackalloc byte[width]` inside the loop | `width * height` | none | process crash on large frames | | `stackalloc byte[width]` before the loop | `width` | none | crash when `width` is huge or hostile | | capped `stackalloc` plus heap fallback | at most the cap | only above the cap | none from the stack | | always `new byte[width]` | none | one array per call | GC pressure on a hot path | ## Choosing the threshold There is no universal number, because the available stack depends on the operating system, the thread (thread-pool and custom threads can have a different stack size from the main thread) and how deep the call chain already is. The documentation's advice is to be conservative. The base class library's own string-manipulation code caps its stack buffers at 256 `char` or 128 `int` values, 512 bytes each, which is a useful order of magnitude. Remember that the cap is per frame: a recursive method that also stack-allocates multiplies it by the recursion depth. ## Catching it before production - **CA2014** (*Do not use stackalloc in loops*) is enabled as a warning by default in .NET 10 and fires on a `stackalloc` inside a loop body. Suppress it only when the loop runs a small, bounded number of times, as the rule's own page says. - **Review rule:** no `stackalloc` whose length comes from input without a constant upper bound in the same expression. - **Test with the largest real inputs**, not the thumbnail in the unit test, and include the fallback path. - **Watch recursion:** a `stackalloc` in a recursive method or in a method called from deep recursion needs a much smaller cap.
- Why can't a try/catch around the C# call recover from the stack overflow?The runtime treats a stack overflow as fatal: managed code cannot stay consistent after an arbitrary overflow, so it prints `Stack overflow.` and terminates the process, and the .NET design guidelines say never to catch `StackOverflowException`. No `catch`, `finally` or `using` cleanup runs. The only defence is never to reserve stack space whose size you do not control.
- Is a fallback rented from ArrayPool<byte>.Shared better than new byte[width] in this converter?On a hot path that sees many large frames, renting avoids a heap allocation per call, but it adds rules: the rented array may be longer than asked and dirty, and it must be returned exactly once in a `finally`. If large frames are rare, `new byte[width]` is simpler and correct; the pooling trade-off belongs to the lesson on pooled buffers.
- Does moving the stackalloc out of the loop fix a converter that is itself called recursively?Only partly. Each call still reserves its own block, so recursion depth multiplies the cost, and the frames between calls add more. A recursive or deeply nested caller needs a much smaller cap, or a heap buffer passed down from the top, so that stack use stays bounded however deep the recursion goes.
- stackalloc memory is released at the end of each loop iteration
- A try/catch around the call turns a stack overflow into a normal error
- Sizing stackalloc from the image width is fine because spans are bounds-checked
- The stack grows on demand, so large stackalloc calls only cost time
- CA2014 is a style warning that can be suppressed everywhere