At compile times, most compilers such as the GNU compiler can identify where an uninitialized variables is used. However, you may need to set flags, such as -Wall
for the GNU compiler.
The value of the variable is already here though it could be any value. Namely it is the "initial" state of the variable.
Therefore, you must initialize the variable to avoid garbage.
When a variable x
is declared, it already allocates a section to the memory &x
which is referred by this variable name. Uninitialized values and variables are already placed in a memory address.
Suppose you initialize a variable v
of type int. It is allocated to a memory address, which is &v
of type int *. Address &v
therefore would be placed to an open unused place in the memory.
Consider this code inside a main function:
int x;
// A number of bytes (in this case, sizeof(int), usually 4 B) already allocated
// starting at a memory location &x.
printf("Value at address %p: %d", &x, x);
// Value at &x may be any int, which is unpredictable
When compiling this code, this warning message occurs, where SOME_DIRECTORY
is an arbitrary directory:
SOME_DIRECTORY>gcc -Wall -g sampleprogram.c -o sampleprogram
sampleprogram.c: In function 'main':
sampleprogram.c:8:5: warning: 'x' is used uninitialized in this function [-Wuninitialized]
printf("Value at address %p: %d", &x, x);
The starting value of a memory, just like circuits, is unpredictable. No matter why your value is random garbage. This is also a form of undefined behavior, which means that the International Standard of C compilers do not set any requirements so anything may happen. This is a very bad bug, can cause multiple hard-to-trace bugs and glitches.