-1

Can you please tell me why the below code is throwing stack overflow error?

 class Program
    {
        static void Main()
        {
            Program.Main();
        }
    }

Why would calling the Main() method would cause filling up of stack memory and eventually throw stack overflow error? This never happens when I run an infinite loop like this-

class Program
    {
        static void Main()
        {
            // Program.Main();
            bool abcd = true;
            while (abcd)
                Console.WriteLine("Running");
        }
    }

Please let me know if this is something to do with the memory management of static members of a class or something related to it. I have looked for answers on Internet but could not find a suitable one.

4
  • 6
    Infinite recursive call - piling up the stack
    – Rafalon
    Apr 6, 2018 at 7:08
  • 2
    in the first one you never not called program.main, so billions of iterations later, you're still going into main and going into main again.. a while loop is a while loop, it doesnt add another level to the stack. Think of it like doing stairs.. the first one you're on a never ending tredmill, the second you went in and stood chatting on the first step.
    – BugFinder
    Apr 6, 2018 at 7:08
  • Because you're calling Main, and inside you're calling Main, and inside you're calling Main, and inside... Method calls going deeper and deeper form a stack, whose size is limited. Once you go past the limit, it blows.
    – user9539019
    Apr 6, 2018 at 7:16
  • 1
    Infinite loop vs recursion. While they may seems similar, they dont do exactly the same. The recurssion consumes stack while the infinite loop does not. As a general rule do NEVER make recursion without an exit condition/check.
    – Cleptus
    Apr 6, 2018 at 7:23

1 Answer 1

12

Each time you call any method1 (the Main method in your case), that creates a new stack frame - that takes up memory. You don't have an infinite amount of memory (particularly on the stack), so eventually you run out of stack space, at which point the exception is thrown.

Note that your method currently doesn't have any local variables or parameters, so each stack frame is relatively small... if you had a lot of local variables, it would throw the exception after fewer calls.

For example:

using System;

class Test
{
    static void Main()
    {
        // Use whichever you want to demonstrate...
        RecurseSmall(1);
        //RecurseLarge(1);
    }

    static void RecurseSmall(int depth)
    {
        Console.WriteLine(depth);
        RecurseSmall(depth + 1);
    }

    static void RecurseLarge(int depth)
    {
        Console.WriteLine(depth);
        RecurseLarge(depth + 1);

        // Create some local variables and try to avoid them being 
        // optimized away... We'll never actually reach this code, but
        // the compiler and JIT compiler don't know that, so they still
        // need to allocate stack space.
        long x = 10L + depth;
        long y = 20L + depth;
        decimal dx = x * depth + y;
        decimal dy = x + y * depth;
        Console.WriteLine(dx + dy);
    }
}

On my machine (with default compilation options), RecurseSmall prints as far as depth 21175; RecurseLarge prints as far as depth 4540.

The JIT compiler is also able to detect some cases where it can use what's called tail recursion to replace the existing stack frame with a new one, at which point the method call effectively doesn't require any more stack space. On my machine, if you compile the above code with:

csc /o+ /debug- /platform:x64

... it runs forever, and will never use much stack space. I generally consider it a bad idea to rely on this optimization though, as it can be hard to predict (and definitely depends on the exact JIT you're using).

Compare all of this with your while loop, which uses whatever extra stack space is required by Console.WriteLine, but that stack space is reclaimed after each call, so you never run out of space.


1 Logically, at least. Methods can sometimes be inlined by the JIT compiler, which will avoid this.

12
  • 2
    Every time you call any method ...
    – Sir Rufo
    Apr 6, 2018 at 7:10
  • @SirRufo: True; edited.
    – Jon Skeet
    Apr 6, 2018 at 7:14
  • Not sure it's related somehow to amount of local variables. Apr 6, 2018 at 7:16
  • 1
    @Alexey: It is; I'm writing code to demonstrate that now.
    – Jon Skeet
    Apr 6, 2018 at 7:17
  • @DaisyShipton you are right, my apologies Apr 6, 2018 at 7:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.