Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ private static void AsExpression()
{
// <SnippetAsExpression>
int length = 1000;
Span<byte> buffer = length <= 1024 ? stackalloc byte[length] : new byte[length];
Span<byte> buffer = length >= 0 && length <= 1024 ? stackalloc byte[length] : new byte[length];
// </SnippetAsExpression>
}

Expand Down Expand Up @@ -72,7 +72,7 @@ private static void LimitStackAllocatedMemory(int inputLength)
{
// <SnippetLimitStackalloc>
const int MaxStackLimit = 1024;
Span<byte> buffer = inputLength <= MaxStackLimit ? stackalloc byte[inputLength] : new byte[inputLength];
Span<byte> buffer = inputLength >= 0 && inputLength <= MaxStackLimit ? stackalloc byte[inputLength] : new byte[inputLength];
// </SnippetLimitStackalloc>
}
}
5 changes: 5 additions & 0 deletions docs/csharp/language-reference/operators/stackalloc.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ You can assign the result of a `stackalloc` expression to a variable of one of t

:::code language="csharp" source="snippets/shared/StackallocOperator.cs" id="AssignToSpan":::

> [!CAUTION]
> This pattern applies a cap only to the `stackalloc` branch of the expression. If the application requires a cap on the `new T[...]` branch of the expression (e.g., to avoid unwanted creation of a one billion-element array), the caller must perform that length check separately.

You don't need to use an [unsafe](../keywords/unsafe.md) context when you assign a stack-allocated memory block to a <xref:System.Span`1> or <xref:System.ReadOnlySpan`1> variable.

When you work with those types, you can use a `stackalloc` expression in [conditional](conditional-operator.md) or assignment expressions, as the following example shows:
Expand Down Expand Up @@ -54,6 +57,8 @@ The amount of memory available on the stack is limited. If you allocate too much

- Avoid using `stackalloc` inside loops. Allocate the memory block outside a loop and reuse it inside the loop.

- Do not provide negative lengths to the `stackalloc` operator. If the length is derived from user input, ensure that the call site _both_ forbids negative values _and_ caps the maximum allowed value, as shown in the above examples. A negative length passed to `new T[...]` will result in a catchable <xref:System.OverflowException> rather than a fatal StackOverflowException.
Comment thread
GrabYourPitchforks marked this conversation as resolved.

The content of the newly allocated memory is undefined. You should initialize it before it's used, either with a `stackalloc` initializer or a method like <xref:System.Span`1.Clear*?displayProperty=nameWithType>.

> [!IMPORTANT]
Expand Down
Loading