0

Why does these the application on the top does not throw a stack overflow exception ? what's up with the recursive method ? I understand that the bottom example creates a deep call stack so it throws the error. But the first example do we use the same space in the memory or does the garbage collector help us.

class ProgramErrorFree
{
    static void Main()
    {
       while(true)
        {
            Console.WriteLine(Guid.NewGuid());
        }
    }
}

class ProgramStackOverFlow
{
    static void Recursive(int value)
    {
        // Write call number and call this method again.
        // ... The stack will eventually overflow.
        Console.WriteLine(value);
        Recursive(++value);
    }

    static void Main()
    {
        // Begin the infinite recursion.
        Recursive(0);
    }
}
Rıfat Erdem Sahin
  • 1,738
  • 4
  • 29
  • 47

1 Answers1

4

Why does these the application on the top does not throw a stack overflow exception ?

Why do you expect it to? From MSDN: StackOverflowException Class:

The exception that is thrown when the execution stack overflows because it contains too many nested method calls.

Your stack never gets deeper than two frames:

  • ProgramErrorFree.Main()
    • Guid.NewGuid()
    • Console.WriteLine()

Whereas your second program the stack frames keep getting stacked:

  • ProgramStackOverFlow.Main()
    • ProgramStackOverFlow.Recursive()
      • ProgramStackOverFlow.Recursive()
        • ProgramStackOverFlow.Recursive()
          • ProgramStackOverFlow.Recursive()
            • ProgramStackOverFlow.Recursive()

And so on, until you run out of stack space.

I think you expect a rapid succession of Guid.NewGuid() to "overflow" the stack, but that's not how that works. See Eric Lippert's blog The Stack Is An Implementation Detail, Part One and further for more information about what the stack is and what it's used for.

See also Running out of ValueType stack space for how to run out of stack space without recursion.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272