Calling functions from each other causing stackoverflow error

721 views Asked by At

I tried following example in C++ with visual studio.

void egg();

void chicken () 
{
    return egg ();
}

void egg () 
{
    return chicken ();
}

int _tmain(int argc, _TCHAR* argv[])
{
    chicken();
    return 0;
}

While running I got error like stackoverflow exception. Could any body please explain me why such error came. I was assuming this will go for infinite loop.

3

There are 3 answers

0
mazhar islam On BEST ANSWER

Each time your chicken () calls egg() and egg() calls chicken (), their return address are pushed onto the stack. As the stack is finite memory, you are getting "error like stackoverflow exception".

Read this for more understanding.

0
Ediac On

Think of it like this, you call chicken(), then you call egg(), which calls chicken(), and then egg(), and so on. It causes a non-finite loop. This leads to overflow after certain amount of iterations, as function calls uses resources from stack, which isn't infinite, and the function calls will remain on stack until the program ends or meets other termination criteria.

0
Gopi On

What you have is infinite loop here.

This can be written as

void chicken () 
{
    return chicken();
}

You are calling the function chicken() recursively and there is no exit condition in the function. All recursive functions should have exit condition else you run out of stack memory and eventually you will hit stackoverflow