繁体   English   中英

预测C代码的输出

[英]Predict the output of the C code

我参加了一次编写该代码的采访,我不得不预测代码的输出。

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

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

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

您提供的代码没有访问者断言的问题。 该代码将:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM