Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/fundamentals/code-analysis/quality-rules/ca2014.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ helpviewer_keywords:
- "CA2014"
author: stephentoub
ms.author: stoub
dev_langs:
- CSharp
---
# CA2014: Do not use stackalloc in loops

Expand All @@ -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.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
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>
}
}