在 C# 中使用单个方法会发生 StackOverflowException 吗?

Nik*_*eni 3 c# stack-overflow stack

当一个方法被无限多次递归调用时,就会发生 StackOverflowException。不同的堆栈帧被分配给每个递归调用——在这种情况下使用多个堆栈帧。众所周知,每个方法调用都会分配一个堆栈帧。在C#中使用单个方法(使用单个堆栈帧)时堆栈会溢出吗?

Mar*_*ell 5

\n

使用单一方法会导致堆栈溢出吗

\n
\n\n

当然:

\n\n
static unsafe void Main()\n{\n    for(int i = 0; i < 50; i++)\n    {\n        // fails on i=18 for me\n        long* ptr = stackalloc long[10 * 1024];\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

当堆栈被完全消耗时,就会发生堆栈溢出。有多种方法可以做到这一点;递归只是其中之一。stackalloc创建一个指向当前堆栈帧处的内存块(或者最近:跨度)的指针,扩展当前堆栈帧;当您从分配它的方法返回(或抛出等)时,它将在概念上被回收(尽管实际上,这仅意味着更改单个数字)。

\n\n
\n\n

另一种方法是创建一个尺寸过大值类型:

\n\n
static class P\n{\n    static void Main() => Foo();\n    static void Foo() => Bar(default);\n    static void Bar(FatStruct2097152\xe2\x80\xac a) => Console.WriteLine(a);\n}\n\nstruct FatStruct64 {\n    private long a, b, c, d, e, f, g, h;\n}\nstruct FatStruct512 {\n    private FatStruct64 a, b, c, d, e, f, g, h;\n}\nstruct FatStruct4096 {\n    private FatStruct512 a, b, c, d, e, f, g, h;\n}\nstruct FatStruct32768 {\n    private FatStruct4096 a, b, c, d, e, f, g, h;\n}\nstruct FatStruct262144 {\n    private FatStruct32768 a, b, c, d, e, f, g, h;\n}\nstruct FatStruct2097152 {\n    private FatStruct262144 a, b, c, d, e, f, g, h;\n}\n
Run Code Online (Sandbox Code Playgroud)\n