Skip to content

Commit 225d23b

Browse files
authored
Add code example for CA2014 rule (#49039) (#49040)
1 parent da9bebe commit 225d23b

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

docs/fundamentals/code-analysis/quality-rules/ca2014.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ helpviewer_keywords:
1010
- "CA2014"
1111
author: stephentoub
1212
ms.author: stoub
13+
dev_langs:
14+
- CSharp
1315
---
1416
# CA2014: Do not use stackalloc in loops
1517

@@ -33,6 +35,10 @@ The C# `stackalloc` expression allocates memory from the current stack frame, an
3335

3436
Move the `stackalloc` expression outside of all loops in the method.
3537

38+
## Example
39+
40+
:::code language="csharp" source="snippets/csharp/all-rules/ca2014.cs" id="snippet1":::
41+
3642
## When to suppress warnings
3743

3844
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.
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
using System;
2+
3+
namespace ca2014
4+
{
5+
public class Example
6+
{
7+
//<snippet1>
8+
// This method violates the rule.
9+
public void ProcessDataBad()
10+
{
11+
for (int i = 0; i < 100; i++)
12+
{
13+
// CA2014: Potential stack overflow.
14+
// Move the stackalloc out of the loop.
15+
Span<int> buffer = stackalloc int[100];
16+
buffer[0] = i;
17+
18+
// ...
19+
}
20+
}
21+
22+
// This method satisfies the rule.
23+
public void ProcessDataGood()
24+
{
25+
Span<int> buffer = stackalloc int[100];
26+
27+
for (int i = 0; i < 100; i++)
28+
{
29+
buffer[0] = i;
30+
31+
// ...
32+
}
33+
}
34+
//</snippet1>
35+
}
36+
}

0 commit comments

Comments
 (0)