预测C代码的输出

use*_*273 0 c stack

我参加了一个代码编写的面试,我不得不预测代码的输出.

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

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

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

Joh*_*all 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 */
Run Code Online (Sandbox Code Playgroud)

  • 我希望如此! (2认同)