I am getting different values for the a variable which is an int.
Although I know I am not initializing it, the value changes from 32767 32766 32765 and 32764 for variable a (with code version 1) and its always 0 with code version 2.
I know I don't have to leave variables uninitialized, just asked this question to see if anybody knew what is happening behind the scenes at runtime, I am using gcc .
whith code version 1
int *b = new int; // <----- this line
whith code version 2
int *b = new int; // <----- same line moved here
You read uninitialized memory. This is undefined behavior. That means the C++ language rules give literally no guarantee what happens when you run this code, at all. You may see the values you observed, nothing at all, crash your PC or set your house on fire. All equally legal outcomes of running this code.
In practice this will only print unpredictable garbage values in the range of
int of course, dependent on what just happens to be left over in your memory and do nothing interesting.
Proof from the standard (N4140) for the non-believers:
When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced (5.17). [ Note: Objects with static or thread storage duration are zero-initialized, see 3.6.2. — end note ] If an indeterminate value is produced by an evaluation, the behavior is undefined except in the following cases:
[8.5 (12)], emphasize mine, the exceptions following this don't apply.
It's an unchecked coincidence in a highly complex system.
That may be the best answer you'll get regarding why uninitialized memory in your computer is showing you the pattern you see.
The c++ statement
new int allocates memory from the heap but it doesn't initialize it. So whatever was on the heap or memory from before is being read. You have to do
int *b = new int(0) to initialize what b is pointing to with 0.