Edit

Share via


CA2014: Do not use stackalloc in loops

Property Value
Rule ID CA2014
Title Do not use stackalloc in loops
Category Reliability
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 9 As warning

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

// 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;

        // ...
    }
}

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.

#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.

[*.{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.

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

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

See also