Home > other >  Why does this recursive method cause a Stack Overflow error when it has no variables?
Why does this recursive method cause a Stack Overflow error when it has no variables?

Time:11-24

I have recursive method like this, which doesn't contain any variable. Why is it throwing a stack overflow exception?

class MainClass
{
    static void Main() => Bark();

    static void Bark() { Bark(); }
}

in the example above, I did not create any variables. If I create any variable(either as a parameter or inside a method), then this is understandable: many variables have been created in the thread's stack, and due to the lack of memory, I get an error.

I don't understand, is the method itself is also stored on the stack? Why am I getting the error?

CodePudding user response:

If you were to debug this piece of code and look at the "call stack" window then you would see it attempt to add Bark to the call stack an infinite amount of times because the recursion has no end point.

CodePudding user response:

The stack frame does not just contain parameters, it also contains a return address, so that the processor knows where to go back to.

Furthermore, the hidden this pointer is also a parameter. To remove that you would need a static function.

There is also the ebp or other stack-frame pointer, which can be pushed onto the stack for each call, depending on the exact calling convention.

So whatever you do, you will definitely get a stack overflow at some point, unless the compiler decides to perform tail-recursion.

CodePudding user response:

I believe what you're expecting to see is tail recursion. Unfortunately C# compiler doesn't support it.

  • Related