Reputation:
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?
Upvotes: 6
Views: 147
Reputation: 40838
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.
Upvotes: 4
Reputation: 959
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.
Upvotes: 1