garbage values in C/C++ [duplicate]

2019-01-27 07:46发布

问题:

Possible Duplicate:
How an uninitialised variable gets a garbage value?

How are garbage values generated in C and C++ ? Does the compiler use some random number generation technique for generating garbage values?

回答1:

If you mean the values of uninitialized variables, those aren't generated. They're just whatever garbage happened to be in that memory location.

int *foo = new int;
std::cout << *foo << std::endl;

New returned a pointer to some address in memory. That bit of RAM has always existed; there is no way to know what was stored there before. If it was just requested from the OS, it'll likely be 0 (the OS will erase memory blocks before giving them out for security reasons). If it was previously used by your program, who knows.

Actually, the results of using an uninitialized variable are undefined. You might get back an unpredictable number, your program may crash, or worse.

Even if you know that its safe to run the above on your platform, you shouldn't rely on that giving a random value. It will appear random, but is probably actually quite a bit more predictable and controllable than you'd like. Plus, the distribution will be nowhere near uniform.



回答2:

If by "garbage values" you mean the values of uninitialized variables, it doesn't -- the value of an uninitialized variable is undefined by the standard. The garbage value you're thinking of is actually just whatever happened to be stored in that memory right before the storage for the variable was allocated from the stack or heap.

That said, some compilers offer debugging aids that will fill uninitialized variables with some well-known "magic number" to help you catch errors of this sort. For example, Microsoft Visual C++ fills uninitialized stack variables with 0xCCCCCCCC. These are specific to the compiler and usually require that you compile with debugging turned on.



回答3:

The memory your program happens to use comes up in some state, controlled by how the electrons flowed at power up, funny properties of the silicion, what was in the memory before, and sometimes cosmic rays.

It isn't random, but it is extremely hard to predict.