Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does an uninitialized variable get a random value?

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.

like image 781
Vinu K S Avatar asked Jun 20 '13 14:06

Vinu K S


People also ask

What happens if you don't initialize a variable?

Initializing a variable means specifying an initial value to assign to it (i.e., before it is used at all). Notice that a variable that is not initialized does not have a defined value, hence it cannot be used until it is assigned such a value.

What does it mean when a variable is uninitialized?

In computing, an uninitialized variable is a variable that is declared but is not set to a definite known value before it is used. It will have some value, but not a predictable one. As such, it is a programming error and a common source of bugs in software.

What is the value of uninitialized variable?

An uninitialized variable has an undefined value, often corresponding to the data that was already in the particular memory location that the variable is using. This can lead to errors that are very hard to detect since the variable's value is effectively random, different values cause different errors or none at all.

What happens when you try to use an uninitialized variable?

So using an uninitialized variable will result in undefined behavior. Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior.


2 Answers

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.

like image 179
Kninnug Avatar answered Sep 28 '22 09:09

Kninnug


The junk may come from two places:

  • When dynamic RAM is powered up, the cells remain in arbitrary state until initialized; this is a property of most hardware implementations of memory
  • When your program runs, it leaves behind values of variables that have been used before but are no longer in scope. This property may be used for attacks: analyzing junk left over by your program may give information to unscrupulous writers of plug ins or other libraries that you use.
like image 45
Sergey Kalinichenko Avatar answered Sep 28 '22 07:09

Sergey Kalinichenko