Reputation: 514
I attended an interview where this code was written and I had to predict the output of the code.
int foo() {
int a;
a = 5;
return a;
}
void main() {
int b;
b = foo();
printf ("The returned value is %d\n", b);
}
The answer was so obvious to me and I answered 5. But the interviewer said the answer is unpredictable since the function would have been popped from the stack after return. Could anyone kindly clarify me on this?
Upvotes: 0
Views: 522
Reputation: 9416
The code as you have presented it does not have the problem the interviewer asserted it does. This code would:
#include <stdio.h>
int * foo ( void ) {
int a = 5; /* as a local, a is allocated on "the stack" */
return &a; /* and will not be "alive" after foo exits */
} /* so this is "undefined behavior" */
int main ( void ) {
int b = *foo(); /* chances are "it will work", or seem to */
printf("b = %d\n", b); /* as we don't do anything which is likely */
return 0; /* to disturb the stack where it lies in repose */
} /* but as "UB" anything can happen */
Upvotes: 6