Call Stack limitation in C# [duplicate]

偶尔善良 提交于 2020-01-24 05:21:09

问题


i wonder how much calls we can perform in stack in c# before we get stack overflow exception

so i decided to write the following code

    static void Method2(int Calls)
    {
        if(!Calls.Equals(0))
            Method1(--Calls);//if more calls remain call method1 and reduce counter
    }
    static void Method1(int Calls)
    {
        if (!Calls.Equals(0))//if more calls remain call method2 and reduce counter
            Method2(--Calls);

    }
    static void Main(string[] args)
    {
        var Calls= 42994;//number of calls(stack overflow appears for large number)
        Method1(Calls);
    }

my question is how compiler decides to throw stack overflow exception is this about memory limitations? once i put 42995 i got stackoverflow but this number is not constant so how this works?


回答1:


Each thread has a stack size. The predefined stack size for the main thread of a program is fixed in the exe file. Each recursive call you make, you consume a little of this stack. When you finish it, the CLR throws a StackOverflowException. For Console/Graphical programs the default stack size should be 1mb of memory. You can't make this memory "bigger" from inside the program (you can use editbin.exe to change it from "outside" the program). This memory isn't dynamic. It is fixed (technically, the address space reserved for this memory is fixed, the memory is really allocated by the Windows OS on demand, probably 4kb at a time, but always up to the reserved address space). You can create secondary threads with the stack size you want.

Note that the handling of the stack in this way is a limitation of x86/x64 architecture, http://en.wikipedia.org/wiki/Stack-based_memory_allocation:

Some processors families, such as the x86, have special instructions for manipulating the stack of the currently executing thread. Other processor families, including PowerPC and MIPS, do not have explicit stack support, but instead rely on convention and delegate stack management to the operating system's application binary interface (ABI).



来源:https://stackoverflow.com/questions/29832311/call-stack-limitation-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!