Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2008
Visual Studio
Visual C#
C# Reference
C# Keywords
 stackalloc
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
C# Language Reference
stackalloc (C# Reference)

The stackalloc keyword is used in an unsafe code context to allocate a block of memory on the stack.

int* fib = stackalloc int[100];

The following example outputs the fibonacci sequence to 100 numbers, in which each number is the sum of the previous two numbers. In the code, a block of memory of sufficient size to contain 100 elements of type int is allocated on the stack, not the heap. The address of the block is stored in the pointer fib. This memory is not subject to garbage collection and therefore does not have to be pinned (by using fixed). The lifetime of the memory block is limited to the lifetime of the method that defines it. You cannot free the memory before the method returns.

stackalloc is only valid in local variable initializers.

Because Pointer types are involved, stackalloc requires unsafe context. For more information, see Unsafe Code and Pointers (C# Programming Guide).

stackalloc is like _alloca in the C run-time library.

Unsafe code is less secure than safe alternatives. However, the use of stackalloc automatically enables buffer overrun detection features in the common language runtime (CLR). If a buffer overrun is detected, the process is terminated as quickly as possible to minimize the chance that malicious code is executed.

C#
class Test
{
    static unsafe void Main()
    {
        const int arraySize = 20;
        int* fib = stackalloc int[arraySize];
        int* p = fib;
        *p++ = 1;
        for (int i = 2; i < arraySize; ++i, ++p)
        {
            // Sum the previous two numbers.
            *p = p[-1] + p[-2];
        }
        for (int i = 0; i < arraySize - 1; ++i)
        {
            Console.WriteLine(fib[i]);
        }

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
/*
Output
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
*/

For more information, see the following section in the C# Language Specification:

  • 18.8 Stack allocation

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2010 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker