Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why a reference declaration influences my pointer?

Case 1

#include <iostream>
using namespace std;
int main() {
    int n = 1;
    // int & r = n;
    int * p;
    cout << &n << endl;
    cout << p << endl;
    return 0;
}

Output 1

0x7fffffffdc94
0

Case 2

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <iostream>
using namespace std;
int main() {
    int n = 1;
    int & r = n;
    int * p;
    cout << &n << endl;
    cout << p << endl;
    return 0;
}

Output 2

0x7fffffffdc8c
0x7fffffffdd90

In Output 2, the pointer p just pointed to the address followed int n. Shouldn’t an unintialized pointer point to some random places?
Why adding a reference declaration influences the address of p pointed to?

>Solution :

Shouldn’t an unintialized pointer point to some random places?

No, an uninitialized pointer points nowhere. It has an indeterminate value. Trying to read and/or print this indeterminate pointer value as you are doing in

cout << p << endl;

has undefined behavior. That means there is no guarantee whatsoever what will happen, whether there will be output or not or whatever the output will be.

Therefore, there is no guarantee that changing any other part of the code doesn’t influence the output you will get. And there is also no guarantee that the output will be consistent in any way, even between runs of the same compiled program or multiple compilations of the same code.


Practically, the most likely behavior is that the compiler will emit instructions that will simply print the value of whatever memory was reserved on the stack for the pointer. If there wasn’t anything there before, it will likely result in a zero value. If there was something there before it will give you that unrelated value.

None of this is guaranteed however. The compiler can also just substitute the read of the pointer value with whatever suits it or e.g. recognize that reading the value has undefined behavior and that it may therefore remove the output statement since it can not be ever reached in a valid program.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading