C# > Interop and Unsafe Code > Unsafe Code > stackalloc
Using stackalloc to Allocate Memory on the Stack
This snippet demonstrates how to use stackalloc
in C# to allocate memory directly on the stack. This is useful for temporary buffers, but be mindful of stack overflow exceptions if allocating large amounts of memory.
Basic stackalloc Example
This code snippet showcases the basic usage of stackalloc
. An integer array of size 10 is created directly on the stack. A unsafe
keyword is used to enable the code using pointers. Then, the array is initialized and the values are printed to the console.
using System;
public class StackAllocExample
{
public static unsafe void Main(string[] args)
{
int size = 10;
// Allocate an array of 10 integers on the stack
int* numbers = stackalloc int[size];
// Initialize the array
for (int i = 0; i < size; i++)
{
numbers[i] = i * 2;
}
// Print the values
Console.WriteLine("Values in the stack-allocated array:");
for (int i = 0; i < size; i++)
{
Console.WriteLine($"numbers[{i}] = {numbers[i]}");
}
}
}
Concepts Behind stackalloc
stackalloc
allocates a block of memory from the current method's stack frame. Memory allocated with stackalloc
is automatically freed when the method returns, without the need for explicit deallocation. This makes it very efficient for short-lived, temporary data structures. However, it can only be used within an unsafe
context.
Real-Life Use Case Section
A common use case for stackalloc
is in image processing or low-level data manipulation where you need a temporary buffer to perform operations. For example, you might use it to temporarily store pixel data during a filtering operation or format conversion.
Best Practices
unsafe
contexts sparingly. Ensure you understand the risks involved with manual memory management.
Interview Tip
When discussing stackalloc
, be prepared to explain its memory management characteristics (automatic deallocation on method return), its performance advantages (stack allocation is faster than heap allocation), and its limitations (stack size limits, unsafe
context requirement).
When to use them
Use stackalloc
when you need a small, temporary buffer within a method, and you need the performance benefits of stack allocation. It's especially useful when you want to avoid the overhead of heap allocation and garbage collection for short-lived data.
Memory Footprint
stackalloc
allocates memory on the stack, which is generally limited in size compared to the heap. The exact stack size varies depending on the operating system and runtime configuration. Exceeding the stack size results in a StackOverflowException
. Because memory is allocated on the stack, the memory is immediately reclaimed when the function returns. There is no garbage collection overhead.
Alternatives
If you need to allocate larger amounts of memory or memory that needs to persist beyond the scope of a method, use heap allocation with new
or ArrayPool
to prevent excessive GC allocations. ArrayPool
is preferable to manually managing memory with new
because the arrays are cached and can be reused, reducing the GC pressure.
Pros
Cons
unsafe
code, which can be more difficult to debug and maintain.
FAQ
-
What happens if I allocate too much memory with
stackalloc
?
You will get aStackOverflowException
, which can crash your application. It's important to carefully manage the size of your stack allocations. -
Do I need to free the memory allocated with
stackalloc
?
No, the memory is automatically freed when the method in which it was allocated returns. -
Can I use
stackalloc
in any C# code?
No, you must use it within anunsafe
context. This requires enabling unsafe code in your project settings.