Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.
7 out of 7 rated this helpful - Rate this topic

stackalloc (C# Reference)

Used in an unsafe code context to allocate a block of memory on the stack.

int* fib = stackalloc int[100];

In the example above, 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 (via fixed). The lifetime of the memory block is limited to the lifetime of the method in which it is defined (there is no way to free the memory before the method returns).

stackalloc is only valid in local variable initializers.

Because Pointer types are involved, stackalloc requires unsafe context. See Unsafe Code and Pointers.

stackalloc is similar to _alloca in the C run-time library.

Unsafe code is inherently less secure than non-unsafe 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.

// cs_keyword_stackalloc.cs
// compile with: /unsafe
using System;
class Test
{
    static unsafe void Main()
    {
        int* fib = stackalloc int[100];
        int* p = fib;
        *p++ = *p++ = 1;
        for (int i = 2; i < 100; ++i, ++p)
        {
            *p = p[-1] + p[-2];
        }
        for (int i = 0; i < 10; ++i)
        {
            Console.WriteLine(fib[i]);
        }
    }
}

Output

 
1
1
2
3
5
8
13
21
34
55

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

  • 18.7 Stack allocation

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

Show:
© 2014 Microsoft. All rights reserved.