-2
#include <iostream>

int main()
{
    int a;
    int *p = &a;
    std::cout << *p << "\n";
}

In this program, when I leave a uninitialized and try getting the output of the pointer, it gives me -2. But when I initialize a with a value, printing *p gives me that value. Why does it give -2 when I leave a uninitialized?

stefan
  • 10,215
  • 4
  • 49
  • 90
Judas
  • 1
  • 3

3 Answers3

6

Because using uninitialized variables, whether direct or indirect (through a pointer or reference), is undefined behavior[1][2][3].


[1] This basically means that those uninitialized variables would have indeterminate values.
[2] I'm sure you'll never like undefined behavior anywhere in your code.
[3] Golden rule: beware of undefined behavior.

Community
  • 1
  • 1
Mark Garcia
  • 17,424
  • 4
  • 58
  • 94
1

a is allocated on stack. It contains whatever was there by chance, when it got allocated. Unlike global, local variables in C are not implicitly initialized to 0 (or anything else).

Probably if you run program multiple times, it will give different value (or not).

0decimal0
  • 3,884
  • 2
  • 24
  • 39
dbrank0
  • 9,026
  • 2
  • 37
  • 55
0

it is illegal in c++ to assign a pointer to a undefined value . a is uninitialized . When you are dereferencing it , it just points to a garbage value .

martincarlin87
  • 10,848
  • 24
  • 98
  • 145
abkds
  • 1,764
  • 7
  • 27
  • 43