stackalloc
Learn to allocate on the stack with stackalloc.
What is stackalloc?
stackalloc allocates a block of memory on the stack instead of the heap. int* buf = stackalloc int[4]; allocates space for 4 ints and returns a pointer.
Stack allocation does not pressure the GC; the block is cleaned up automatically when the method returns. It is valid only in an unsafe context and overrunning its bounds is unsafe, so it must be used carefully.
stackalloc and Span
In modern C#, the result of stackalloc can be assigned directly to Span<T>: Span<int> buf = stackalloc int[4];. This uses stack allocation safely without an unsafe context.
Span checks bounds, so there is no overrun risk. This style is preferred over pointer-based stackalloc in most cases and keeps the code both safe and fast.
Exercise Sum values with stackalloc
Make Main unsafe. Allocate 2 ints with int* buf = stackalloc int[2];. Assign buf[0] = 5; buf[1] = 9; and print the sum with Console.WriteLine(buf[0] + buf[1]);.
Show example solution
unsafe static void Main() { int* buf = stackalloc int[2]; buf[0] = 5; buf[1] = 9; Console.WriteLine(buf[0] + buf[1]); }
Example solution:
using System;
class Program
{
unsafe static void Main()
{
int* buf = stackalloc int[2];
buf[0] = 5;
buf[1] = 9;
Console.WriteLine(buf[0] + buf[1]);
}
}
Test yourself
-
Match the memory regions
- stackalloc
- Allocates on the stack
- heap
- Managed by the GC
- stack
- Cleaned up on method return
- int*
- Pointer to int
-
Where does stackalloc allocate memory?
- Stack
- Heap
- LOH
- Managed array
Show answer
Stack — Correct. stackalloc allocates on the stack, not the heap.
-
stackalloc declaration
int* buf = ____ int[4];Show answer
int* buf = stackalloc int[4];