Skip to content

Instantly share code, notes, and snippets.

@itczl22
Last active November 5, 2016 07:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itczl22/6e629664d86f90061e41c83d034e4453 to your computer and use it in GitHub Desktop.
Save itczl22/6e629664d86f90061e41c83d034e4453 to your computer and use it in GitHub Desktop.
未初始化的局部变量
#include<stdio.h>
void foo(void) {
int tmp;
printf("%d\n", tmp);
tmp = 999;
}
int main() {
foo(); // 0
// printf("hello\n");
// int i = 10;
foo(); // 999
return 0;
}
/*
* gcc对于未初始化的临时变量的值是不确定的, 对于一个未使用过的地址一般是0
* 第一次foo()输出0, 此时tmp对应的地址的赋值为999, foo结束后tmp被释放
* 第二次foo()的时候, 两次函数栈的栈顶一样, 即两次tmp地址一样
* 所以里边的值是上次的999, 因此第二次foo()输出999
*
* 如果第一次foo()之后调用了printf, 那么函数栈会发生变化, 第二次的foo()就不会复用第一次的地址
* 所以输出的又会是不确定的值
* [而无论有没有int i = 10; 都不会影响上边的结论, 因为普通的栈变量不影响函数栈]
*
* 不过实际开发中最好对所有的变量做初始化, 避免不必要的bug
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment