Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack overflow error or exception?

Tags:

c++

recursion

Why does the following ends up with no error?

void func()
{
   func();
}

int main()
{
   func();
}
like image 826
Ant Avatar asked Mar 30 '11 23:03

Ant


2 Answers

In theory, it would overflow the stack (because, even if no local variables are used, each call would add the previous return address on the stack); in practice, with optimizations enabled, it doesn't overflow because of tail call optimization, which actually avoids any resource consumption transforming the call in a jump, thus not consuming the stack.

This can be easily seen by examining the optimized assembly generated by the OP code:

func():
.L2:
        jmp     .L2
main:
.L4:
        jmp     .L4

func is optimized to an infinite loop, both the "freestanding version" and the inlined call in main.

Notice that this is coherent with the C++ standard for the "as if" rule: the compiled program must run as if it were what you requested in the code (in terms of effect), and since the stack size is just an implementation limit, the generated code that uses a call and the one that uses a jmp are equivalent.

But: this is an even more particular case, as the standard even says that infinite looping (defined as "not terminating and not having some side-effect") is actually undefined behavior, so in theory the compiler would be allowed to omit that call entirely.

like image 177
Matteo Italia Avatar answered Oct 03 '22 16:10

Matteo Italia


Likely, your compiler optimized it away and turned it into a while(true){} construct.

like image 32
Puppy Avatar answered Oct 03 '22 14:10

Puppy