C++ 中未初始化的变量行为
我自己查了一下,我写了一个这样的程序
I've checked myself, I wrote a program like this
int main() {
int i;
cout << i;
return 0;
}
我运行了几次程序,结果一直都是一样的,为零.我在 C 中尝试过,结果是一样的.
I ran the program a few times and the result was same all the time, zero. I've tried it in C and the result was the same.
但是我的教科书上说
如果您不初始化已定义的变量在函数内部,变量值保持未定义.这意味着元素承担以前驻留在内存中该位置的任何值.
If you don’t initialize an variable that’s defined inside a function, the variable value remain undefined.That means the element takes on whatever value previously resided at that location in memory.
当程序总是将空闲内存位置分配给变量时,这怎么可能?怎么可能不是零(我假设默认的可用内存值为零)?
How's this possible when the program always assign a free memory location to a variable? How could it be something other than zero(I assume that default free memory value is zero)?
推荐答案
当程序总是分配空闲内存时,这怎么可能位置到变量?它怎么可能不是零呢?
How's this possible when the program always assign a free memory location to a variable? How could it be something rather than zero?
让我们看一个实际的实现示例.
Let's take a look at an example practical implementation.
假设它利用堆栈来保存局部变量.
Let's say it utilizes stack to keep local variables.
void
foo(void)
{
int foo_var = 42;
}
void
bar(void)
{
int bar_var;
printf("%d
", bar_var);
}
int
main(void)
{
bar();
foo();
bar();
}
上面完全损坏的代码说明了这一点.在我们调用 foo 之后,放置 foo_var 的堆栈上的某个位置被设置为 42.当我们调用 bar 时,bar_var 占据了那个确切的位置.事实上,执行代码会打印 0 和 42,表明除非初始化,否则无法依赖 bar_var 值.
Totally broken code above illustrates the point. After we call foo, certain location on the stack where foo_var was placed is set to 42. When we call bar, bar_var occupies that exact location. And indeed, executing the code results in printing 0 and 42, showing that bar_var value cannot be relied upon unless initialized.
现在应该清楚本地变量初始化是必需的.但是 ma??in 会是个例外吗?有什么东西可以与堆栈一起玩,结果给我们一个非零值吗?
Now it should be clear that local variable initialisation is required. But could main be an exception? Is there anything which could play with the stack and in result give us a non-zero value?
是的.ma??in 不是程序中执行的第一个函数.事实上,设置所有内容需要 吨 的工作.任何这项工作都可以使用堆栈并在其上留下一些非零.您不仅不能期望在不同的操作系统上具有相同的值,而且它很可能在您现在使用的系统上突然发生变化.有兴趣的可以google一下动态链接器".
Yes. main is not the first function executed in your program. In fact there is tons of work required to set everything up. Any of this work could have used the stack and leave some non-zeros on it. Not only you can't expect the same value on different operating systems, it may very well suddenly change on the very system you are using right now. Interested parties can google for "dynamic linker".
最后,C 语言标准甚至没有术语堆栈.局部变量的位置"留给编译器.它甚至可以从给定寄存器中发生的任何事情中得到随机的废话.它真的可以是完全任何东西.事实上,如果触发了未定义的行为,编译器可以自由地做任何想做的事情.
Finally, the C language standard does not even have the term stack. Having a "place" for local variables is left to the compiler. It could even get random crap from whatever happened to be in a given register. It really can be totally anything. In fact, if an undefined behaviour is triggered, the compiler has the freedom to do whatever it feels like.
相关文章