C++: Uninitialized variables garbage

喜你入骨 提交于 2019-11-27 08:12:21

问题


int myInt;
cout << myInt; // Garbage like 429948, etc

If I output and/or work with uninitialized variables in C++, what are their assumed values?

  • Actual values in the memory from the "last user"?

e.g.: Program A is closed, it had an int with the value 1234 at 0x1234 -> I run my program, myInt gets the address 0x1234, I output it like above -> 1234

  • Is it just random garbage?

回答1:


"Random garbage" but with emphasis on "garbage", not on "random" – i.e., absolutely arbitrary garbage without even any guarantee of "randomness" – the compiler and runtime systems are allowed to have absolutely anything there (some systems may always give zeros, other might give arbitrary different values, etc., etc.).




回答2:


It's not even guaranteed to be a value at all. Trying to read the int, anything can happen (such as a signal sent causing your program to terminate). With particular importance in real life programming, switching on a not initialized bool can cause you hit neither true nor false cases.




回答3:


Its value is indeterminate. (§8.5/9)

There's no use trying to get meaningful data from it. In practice, it's just whatever happened to be there.

Most compilers will pack "meaningful" debug data in there in a debug build. For example, MSVC will initialize things to 0xCCCCCCCC. This is removed in an optimized build, of course.




回答4:


the integer is a variable on the stack since it is a local variable. As long as it has not been initialized, the data on the stack is as-is. It is (part of) a previously used data. So it is garbage, but it is not random since given the executable and a begin state, the value is predictable. Predicting is hard since you have to take into the account the OS, the compiler, etc and moreover it is very pointless.




回答5:


Program A is closed, it had an int with the value 1234 at 0x1234 -> I run my program, myInt gets the address 0x1234...

Note also that because of virtual memory in modern operating system what Program A called address 0x1234 is unlikely to actually refer to the same space in physical memory as what your program calls address 0x1234.



来源:https://stackoverflow.com/questions/2659546/c-uninitialized-variables-garbage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!