diff --git a/docs/fundamentals/code-analysis/quality-rules/ca2014.md b/docs/fundamentals/code-analysis/quality-rules/ca2014.md index ed36a1fed65d3..830bba5a67ce9 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca2014.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca2014.md @@ -10,6 +10,8 @@ helpviewer_keywords: - "CA2014" author: stephentoub ms.author: stoub +dev_langs: +- CSharp --- # CA2014: Do not use stackalloc in loops @@ -33,6 +35,10 @@ The C# `stackalloc` expression allocates memory from the current stack frame, an Move the `stackalloc` expression outside of all loops in the method. +## Example + +:::code language="csharp" source="snippets/csharp/all-rules/ca2014.cs" id="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. diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2014.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2014.cs new file mode 100644 index 0000000000000..ae670449897ab --- /dev/null +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2014.cs @@ -0,0 +1,36 @@ +using System; + +namespace ca2014 +{ + public class 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 buffer = stackalloc int[100]; + buffer[0] = i; + + // ... + } + } + + // This method satisfies the rule. + public void ProcessDataGood() + { + Span buffer = stackalloc int[100]; + + for (int i = 0; i < 100; i++) + { + buffer[0] = i; + + // ... + } + } + // + } +}