Search code examples
c#recursionstack-overflow

Why stack overflow exception is thrown on different call numbers?


Consider this code:

    private static int i = 0;

    static void Main(string[] args)
    {
        DoSomething();
        Console.ReadLine();
    }

    public static void DoSomething()
    {
        Console.WriteLine(i);
        ++i;
        DoSomething();
    }

Each time I run it, I get StackOverflowException on a different value of i variable. For example 16023, 16200, 16071.

What's the reason behind this? Is it a bug in C# compiler?


Solution

  • The behavior of unbounded recursion is implementation defined. Implementation defined means it can do anything. The program can terminate at any time (or never terminate), throw an unhandled exception, or whatever. For example compiling as MSIL and running on a 64-bit OS, the program never terminates for me. This is because the jitter is permitted to turn the recursion into a loop, which the 64-bit jitter does. Asking why it terminates at a particular value serves no practical purpose because the runtime is permitted to do anything.