0

I just started learning c++ and encountered some weird behavior, the results of the below code is:

0x7ffee729ba58

Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

Code:

int i  = 23;
int &ref_i = i;
cout << &i << endl;

int *p;
cout << *p << endl;

But if I remove the second line int &ref_i = i;, the reuslt is as expected:

0x7ffee262ca58

0

Process finished with exit code 0

Why? Thanks!

Sky
  • 79
  • 1
  • 8
  • 3
    `p` isn't Initialized, so using it invokes UB. And deference a pointer to nowhere also invokes UB – phuclv Aug 17 '22 at 02:57
  • 1
    I am new to c++, but I feel like it is a kind of undefined behavior. You get random garbage. Don't try to identify the reason, because it is all garbaged. – cppBeginner Aug 17 '22 at 02:57
  • Thank you, all! Your comments cleared my doubt. – Sky Aug 17 '22 at 02:59
  • 1
    What you see is that C++ will not initialize any of your variables for you until you tell C++ to do so. In this case *p is a pointer pointing to an int (address of int) but it has not been initialized and my not anywhere valid. Where it points is random and your program may give different "results" each time you run it. (This is what is refered to by undefined behavior) – Pepijn Kramer Aug 17 '22 at 03:00
  • The code provided does not compile. – Eljay Aug 17 '22 at 03:01
  • @Elijay :: it compiles :: https://coliru.stacked-crooked.com/a/811f65efebd4f673 – cppBeginner Aug 17 '22 at 03:04
  • It compiles only after adding `include` directives, a `using` statement, and placing the code inside a function. – user4581301 Aug 17 '22 at 05:30

0 Answers0