Search code examples
c++stack-overflowiostreammutual-recursion

Program returns a value of -1073741571 instead of going forever


i'm learning about functions and decided to make a loop where two function(in this case funcA and funcB ) call each other forever but it stops execution after some time. The code looks like this:

#include <iostream>

void funcA(); //forward declaration

//funcB calls funcA 
void funcB()
{
    funcA();
}

//funcA prints 1 and calls funcB again 
void funcA()
{
    std::cout<<1;
    funcB();
}

//main calls funcB
int main()
{
    funcB();
    return 0;
}  

the returned value is -1073741571 (0xC00000FD). can you expain why this happens?


Solution

  • Ok so since this is gcc on Windows 10 take a look on this goodbolt

    Without any optimization enabled both functions are explicitly called.

    b():
            push    rbp
            mov     rbp, rsp
            call    foo()
            call    a()
            nop
            pop     rbp
            ret
    a():
            push    rbp
            mov     rbp, rsp
            call    b()
            nop
            pop     rbp
            ret
    

    As other answer point out each call leaves on stack information how to come back to function which called function. Now since functions never return this information is never removed from stack, but is constantly added. As a result you have got stack overflow which on Windows is indicated by value 0xC00000FD.

    Now if you enable optimization (-O2) compiler is able to figure out this is infinitive loop (using technique called tail recursion).

    b():
            sub     rsp, 8
    .L2:
            call    foo()
            jmp     .L2
    a():
            sub     rsp, 8
    .L6:
            call    foo()
            jmp     .L6
    

    So with optimization enabled you will have infinitive loop as you are expecting.