The value of an uninitialized local integer variable of storage class auto
, that is stored in the stack area, is undefined. For this reason, printing it, a random value is absolutely expected.
That's why, in your output
abc 1
4
abc Random_Value
4
the value 1
is garbage as well.
In fact it is the first location in the stack, and its value could be different changing system and/or compiler. My guess is that its value is 1 because it represents a "ghost argc
" that, being main a very special function, is present even if the function is defined without parameters, and its value is 1.
Since argc
represents the number of parameters used to call your program from command line (at least 1: the executable name) there's a way to verify this hypotesis: call your program in this way
executableName foo
This would make argc become 2, so the value shown by that first printf
should become 2
as well.
Out of curiosity, I tested this hypotesis by compiling your second example on my machine (DevC++ with gcc
compiler under W10 64bit OS). I confirmed two statements:
- When undefined behavior occurs, changing environment leads to a change in the output
argc
is present in the stack and affects the initial value of the uninitialized local variables
Output after executing uninitVars.exe
abc
0
abc
1
Output after executing uninitVars.exe dog
abc
0
abc
2
Output after executing uninitVars.exe dog cat
abc
0
abc
3
So it seems that the first four bytes of my stack are always set to 0 (are they the location of the return value?) and that the second one is actually argc
, even if it is not explicitly defined in the main()
prototype.
The second print, instead, shows different values because it is defined after two printf
calls, and their execution write several bytes in the stack (some of them are addresses, and that explains why the value is always different, as the addresses of a process are virtual and always different).