C++: Uninitialized variables garbage

前端 未结 5 1030
攒了一身酷
攒了一身酷 2020-12-12 02:38
int myInt;
cout << myInt; // Garbage like 429948, etc

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

相关标签:
5条回答
  • 2020-12-12 03:12

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

    0 讨论(0)
  • 2020-12-12 03:19

    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 讨论(0)
  • 2020-12-12 03:23

    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.

    0 讨论(0)
  • 2020-12-12 03:26

    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.

    0 讨论(0)
  • 2020-12-12 03:26

    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.

    0 讨论(0)
提交回复
热议问题