In C#, stackalloc
is used to allocate memory on the stack; however, it can only be used in an unsafe context.
The following restrictions apply when using stackalloc
:
stackalloc
inside a method call is freed when the method returns.stackalloc
cannot be explicitly freed.stackalloc
; therefore, pinning it using a fixed
statement is not required.Following C# 7.0+, stackalloc
can be used in an unsafe context, provided that the value returned by a stackalloc
expression is stored inside System.Span<T>
or System.ReadOnlySpan<T>
. The following code presents an example:
class Program {static void Main() {System.Span<int> oddNumbers = stackalloc int[5];for (int i = 0; i < 5; i++) {oddNumbers[i] = i * 2 + 1;}for (int i = 0; i < 5; i++) {System.Console.WriteLine(oddNumbers[i]);}}}
1
3
5
7
9
In the example above, the oddNumber
variable is allocated memory on the stack to store five integers using the stackalloc
keyword. The first five odd numbers are stored inside oddNumber
and are printed on the console.
The stackalloc
memory address can also be stored inside a pointer; however, this requires the unsafe
context to be used. The following code provides an example:
class Program {static void Main() {unsafe {int * oddNumbers = stackalloc int[5];for (int i = 0; i < 5; i++) {oddNumbers[i] = i * 2 + 1;}for (int i = 0; i < 5; i++) {System.Console.WriteLine(oddNumbers[i]);}}}}
1
3
5
7
9
The example above contains almost the same code as the previous example. However, the oddNumber
variable is an integer pointer in this example. Moreover, since we are storing the memory address returned from stackalloc
in a pointer variable, we have enclosed the above code in the unsafe
context.
Free Resources