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
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.
#pragma warning disable CA2014
// The code that's violating the rule is on this line.
#pragma warning restore CA2014To disable the rule for a file, folder, or project, set its severity to none in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA2014.severity = noneTo 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 = noneFor more information, see How to suppress code analysis warnings.