Favicon

Stackalloc expression

Peponi12/29/20242m

C#
SyntaxExpressionstackalloc

1. Introduction

stackalloc 식은 스택에 메모리 블록을 할당한다. stackalloc을 통해 할당된 메모리 블록은 메서드가 반환될 때 자동으로 해제되며 명시적으로 해제가 불가능하다. 또한 할당된 메모리 블록은 GC의 대상이 아니며 fixed 문을 사용하여 피닝하지 않아도 된다.

2. Example

stackalloc 식은 다음 형식 중 하나에 할당할 수 있다.

  • System.Span<T> : T비관리형 형식

    static void Main(string[] args)
    {
        Span<int> foo = stackalloc int[3] { 1, 2, 3 };
        Span<int> bar = stackalloc int[] { 1, 2, 3 };
     
        Console.WriteLine(foo[1]);
        Console.WriteLine(bar[1]);
    }
     
    /* output:
    2
    2
    */
  • System.ReadOnlySpan<T> : T는 비관리형 형식

    static void Main(string[] args)
    {
        ReadOnlySpan<int> foo = stackalloc int[3] { 1, 2, 3 };
        ReadOnlySpan<int> bar = stackalloc int[] { 1, 2, 3 };
     
        Console.WriteLine(foo[1]);
        Console.WriteLine(bar[1]);
    }
     
    /* output:
    2
    2
    */
  • Pointer

    unsafe static void Main(string[] args)
    {
        int* foo = stackalloc int[3];
     
        for (int i = 0; i < 3; i++)
        {
            foo[i] = i + 1;
        }
     
        Console.WriteLine(foo[1]);
    }
     
    /* output:
    2
    */

CAUTION

stackalloc 식을 루프 내에서 할당하면 반복적으로 메모리 할당을 수행한다. StackOverflowException이 일어날 수 있기 때문에 주의하여 사용한다.

unsafe static void Main(string[] args)
{
    int loopIndex = 10;
    while (--loopIndex > 0)
    {
        Span<int> ints = stackalloc int[2] { 1, 2 };    // CA2014
        fixed (int* foo = &ints[1])
        {
            Console.WriteLine($"{(long)foo:X2}");
        }
    }
}
 
/* output:
B32B17E7A4
B32B17E794
B32B17E784
B32B17E774
B32B17E764
B32B17E754
B32B17E744
B32B17E734
B32B17E724
*/

3. 참조 자료