Suppose I declare a variable x
and leave it uninitialized. I go on to print its value. I see some junk.
Where does it come from? Also why is it not used to generate random numbers? I mean instead of using a pseudo random generator.
Suppose I declare a variable x
and leave it uninitialized. I go on to print its value. I see some junk.
Where does it come from? Also why is it not used to generate random numbers? I mean instead of using a pseudo random generator.
The 'random' value is simply what's left in memory at that location. Memory usually isn't erased/zeroed when it's freed so whatever was there will linger until it's overwritten.
The junk may come from two places:
The value of an uninitialized variable is the value present at the corresponding memory area before it has been assigned to this variable. Most of the time it is unpredictable and depend of whatever happened before within this memory area.
This is actually sometimes used as additional entropy to generate pseudo-random numbers. Years ago, a Debian developers thought that an uninitialized variable was a bug in OpenSSL and set it to zero. Then the generated keys became somewhat guessable and now every Debian users have to install a long list of black listed keys on their machines.
The short answer? It depends on your compiler - but don't do it.
The long answer:
Accessing the value of an uninitialized POD (plain old data, such as int
) type invokes undefined behavior, which means the C standard does not place any requirements on a conforming implementation in this situation. Thus, a compiler is permitted to emit machine code that launches nethack
, formats your hard drive, or does nothing at all, while still conforming to the C standard - as long as it can prove that undefined behavior occurs anywhere in your program.
(Also read: What Every C Programmer Should Know About Undefined Behavior)
So, what actually (probably) happens?
On most modern compilers without optimization enabled, the compiler will simply assign a slot on the stack (or a register) to the variable, then access whatever was at that location before when asked. The result is what appears to be "random memory", though in reality it's not very random at all.
What might happen if I enabled optimizations?
If you then go to compile your code on a higher optimization level (or the compiler is updated and now optimizes more aggressively), all bets are off. For example, the compiler may remove any calls that involve x
, assign x
to the same location as some other variable (arguing that x
cannot possibly be used, since it isn't initialized yet), or any other combination of strange effects.
In other words, the moment you access that uninitialized variable, your program can start doing anything outside your control. Don't do it - here be dragons.