预测C代码的输出

时间:2016-02-25 05:17:40

标签: c stack

我参加了一个采访,其中编写了这段代码,我不得不预测代码的输出。

int foo() {
  int a;
  a = 5;
  return a;
}

void main() {
  int b;
  b = foo();
  printf ("The returned value is %d\n", b);
}

答案对我来说非常明显,我回答了5.但是面试官说答案是不可预测的,因为函数会在返回后从堆栈中弹出。有人可以在此澄清我吗?

1 个答案:

答案 0 :(得分:6)

您提供的代码没有面试官断言的问题。这段代码将:

#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 */