C程序栈

标签 c

#include<stdio.h>

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

void bar() {
  int a = 7;
}

void foobar() {
    int a = 97;
}

int main() {
    int* p = foo();
    bar();
    foobar();
    printf("%d", *p);

    return 0;
}

我无法理解此行为背后的概念。 为什么foobar函数输出的总是局部变量a的值?

最佳答案

不能这样做:

int* foo() {
  int a = 5;
  return &a;  /* variable "a" is out of scope once "foo()" returns */
}

这是 "undefined behavior" .结果可能因环境而异,编译器与编译器不同,甚至运行不同。但它总是“垃圾”。

关于C程序栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32160269/

相关文章:

c - 我如何能够在 C 中创建路由表查找?

c - 我错误地使用了 close() 吗?

在C中将时间转换为毫秒

c - 字符串数组的部分副本

c - 在 for 循环中重复使用 switch 语句

c - 如何在 C 中将 token 字符中的值设置为名为 customerData[][] 的数组?

c - 如何在终端中用c语言打印一组随机字母?

python - 使用 Pycparser 解析变量依赖关系

c - 这条代码行是做什么的?

c - C中的多线程死锁