What are stackalloc array support initializers in C#?

Overview

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:

  • The memory allocated using stackalloc inside a method call is freed when the method returns.
  • Memory allocated by stackalloc cannot be explicitly freed.
  • Garbage collection doesn’t work on memory allocated via stackalloc; therefore, pinning it using a fixed statement is not required.

Enhancements

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]);
}
}
}

Output

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]);
}
}
}
}

Output

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

Copyright ©2024 Educative, Inc. All rights reserved