다음을 통해 공유


stackalloc (C# Reference)

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

int* block = stackalloc int[100];

Remarks

The keyword is valid only in local variable initializers. The following code causes compiler errors.

int* block;
// The following assignment statement causes compiler errors. You
// can use stackalloc only when declaring and initializing a local 
// variable.
block = stackalloc int[100];

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.

The following example calculates and displays the first 20 numbers in the Fibonacci sequence. Each number is the sum of the previous two numbers. In the code, a block of memory of sufficient size to contain 20 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.

Example

class Test
{
    static unsafe void Main()
    {
        const int arraySize = 20;
        int* fib = stackalloc int[arraySize];
        int* p = fib;
        // The sequence begins with 1, 1.
        *p++ = *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; ++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
6765
*/

Security

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# Language Specification

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

See Also

Reference

C# Keywords

Operator Keywords (C# Reference)

Unsafe Code and Pointers (C# Programming Guide)

Concepts

C# Programming Guide

Other Resources

C# Reference