Jaydeep Godhani
Jaydeep Godhani

Reputation: 23

Why this program compiled successfully but failed to run?

#include <stdio.h>
main()
{
int i=5;
    if(--i)
    {
        main();
        printf("%d ",i);
    }

Note that if we make int i as static then answer would be 0000.

Upvotes: 0

Views: 704

Answers (3)

jfMR
jfMR

Reputation: 24738

The variable i has the value 5 every time the function main() is entered (each call to main() owns its own copy of that variable on the stack). There is no recursion termination, because the condition for the recursion termination is never met (i.e.: --i never evaluates to zero). Therefore, main() is recursively called until there is no more place on the stack.

If you however declare i as static, there is a single shared copy of the variable i for all calls to main(). The recursion termination condition is met when --i evaluates to zero.

Upvotes: 3

Geo
Geo

Reputation: 155

The code itself is correct, the program will compile without any problem. The problem is that the condition if (--i) will always evaluate to true as each time main is recursively called, a new local i variable is created and it is always worth 5. As you stack more and more calls, the program will terminate by SIGSEGV when the stack can not grow anymore. You can observe this with Valgrind :

==10972== Memcheck, a memory error detector
==10972== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==10972== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==10972== Command: ./a.out
==10972==
==10972== Stack overflow in thread #1: can't grow stack to 0xffe801000
==10972==
==10972== Process terminating with default action of signal 11 (SIGSEGV)

The reason why the program outputs 0000 when you declare i as a static variable is because i is not redeclared at every main call. So basically main is recursively called until i is worth 0. Then, all the stacked printfs are executed but as i is worth 0 in each of these stacked calls, you will see 0000. The static keyword makes all the main calls actually refering to the same i variable and not copies.

Upvotes: 0

Akash Deep Sharma
Akash Deep Sharma

Reputation: 29

It runs out of space(on stack) because it is making a call to main() indefinetely

Upvotes: 0

Related Questions