Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 949
zeroG Avatar asked Sep 13 '25 02:09

zeroG


2 Answers

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.

like image 190
Charlieface Avatar answered Sep 14 '25 17:09

Charlieface


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.

like image 29
Sara Gowen Avatar answered Sep 14 '25 17:09

Sara Gowen