C#idiomatic C#
ca2014fundamentals/code-analysis/quality-rules

Code analysis

CA2014: Do not use stackalloc in loops

Learn about code analysis rule CA2014: Do not use stackalloc in loops

CA2014 Reliability enabled by default in .NET 10: As warning
Fix is breaking or non-breaking Non-breakingApplicable languages C#

Cause

Using the C# stackalloc expression inside of a loop.

Rule description

The C# stackalloc expression allocates memory from the current stack frame, and that memory may not be released until the current method call returns. If stackalloc is used in a loop, it can lead to stack overflows due to exhausting the stack memory.

How to fix violations

Move the stackalloc expression outside of all loops in the method.

Example

sample · csharpdocs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2014.cssnippet1

csharp
using System;

namespace ca2014
{
    public class Example
    {
        //<snippet1>
        // This method violates the rule.
        public void ProcessDataBad()
        {
            for (int i = 0; i < 100; i++)
            {
                // CA2014: Potential stack overflow.
                // Move the stackalloc out of the loop.
                Span<int> buffer = stackalloc int[100];
                buffer[0] = i;

                // ...
            }
        }

        // This method satisfies the rule.
        public void ProcessDataGood()
        {
            Span<int> buffer = stackalloc int[100];

            for (int i = 0; i < 100; i++)
            {
                buffer[0] = i;

                // ...
            }
        }
        //</snippet1>
    }
}

When to suppress warnings

It may be safe to suppress the warning when the containing loop or loops are invoked only a finite number of times, such that the overall amount of memory allocated across all stackalloc operations is known to be relatively small.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

csharp
#pragma warning disable CA2014
// The code that's violating the rule is on this line.
#pragma warning restore CA2014

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

ini
[*.{cs,vb}]
dotnet_diagnostic.CA2014.severity = none

To disable this entire category of rules, set the severity for the category to none in the configuration file.

ini
[*.{cs,vb}]
dotnet_analyzer_diagnostic.category-Reliability.severity = none

For more information, see How to suppress code analysis warnings.

See also