6

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?

7
  • AFAIK, the CLR makes no guarantees about the maximum depth of the stack. Commented Jun 15, 2013 at 7:22
  • What is the maximum depth of the stack? Commented Jun 15, 2013 at 7:26
  • 1
    That's my point - the CLR doesn't provide any guarantees. And so: Is it a bug in C# compiler? No. But 16k is really, really pushing it. Commented Jun 15, 2013 at 7:27
  • I have got same exception Commented Jun 15, 2013 at 7:42
  • Execute the same code in Release mode and the number comes as 128800... This is about 80 times higher Commented Jun 15, 2013 at 7:44

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Nice explanation. So, runtime has full authority to either stop and throw an exception, or continue recurring.
I'm not sure I'd really describe tail-call as a loop, but I guess it conveys the same
1

Your stacksize isn't big enough.

You can increase your default stacksize by starting a new thread and define the new stacksize in the constructor:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApplication3
{
class Program
{
    private static int i = 0;

    static void Main(string[] args)
    {
        Thread T = new Thread(DoSomething, 100000000);
        T.Start();
        Console.ReadLine();



    }

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

 }
}

Stackoverflow now happens at 1.5 million recursive calls.

1 Comment

There is no stack size big enough for an infinite dive (excluding tail-call)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.