Skip to content

Commit df66bc9

Browse files
BillWagneradegeo
andauthored
Clarify the unitialized nature of stackalloc memory. (#41630)
* Clarify the unitialized nature of stackalloc memory. Responding to anonymous feedback. * Update docs/csharp/language-reference/operators/stackalloc.md * Apply suggestions from code review * Apply suggestions from code review * Apply suggestions from code review Co-authored-by: Andy (Steve) De George <[email protected]> --------- Co-authored-by: Andy (Steve) De George <[email protected]>
1 parent df92915 commit df66bc9

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

docs/csharp/language-reference/operators/stackalloc.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,10 @@ The amount of memory available on the stack is limited. If you allocate too much
4949
5050
- Avoid using `stackalloc` inside loops. Allocate the memory block outside a loop and reuse it inside the loop.
5151

52-
The content of the newly allocated memory is undefined. You should initialize it before the use. For example, you can use the <xref:System.Span%601.Clear%2A?displayProperty=nameWithType> method that sets all the items to the default value of type `T`.
52+
The content of the newly allocated memory is undefined. You should initialize it, either with a `stackalloc` initializer, or a method like <xref:System.Span%601.Clear%2A?displayProperty=nameWithType> before it's used.
53+
54+
> [!IMPORTANT]
55+
> Not initializing memory allocated by `stackalloc` is an important difference from the `new` operator. Memory allocated using the `new` operator is initialized to the 0 bit pattern.
5356
5457
You can use array initializer syntax to define the content of the newly allocated memory. The following example demonstrates various ways to do that:
5558

0 commit comments

Comments
 (0)