-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
  • 9,915
  • 3
  • 47
  • 87
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
  • 16,898
  • 3
  • 55
  • 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,828
  • 2
  • 22
  • 38
dbrank0
  • 8,606
  • 2
  • 39
  • 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,397
  • 24
  • 97
  • 143
abkds
  • 1,717
  • 6
  • 26
  • 42