开发者

C++: Uninitialized variables garbage

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 pro开发者_C百科gram, myInt gets the address 0x1234, I output it like above -> 1234

  • Is it just random garbage?


"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.).


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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜