0

I am writing the following to pass pointers by reference. However, when I try to dereference the pointers, it is giving unexpected values.

void passPointers(int* &a){
    int p = 5;
    a = &p;
}
int main(){
  int x = 3;
  int *y= &x;
  cout<<"y is "<<y<<" *y is "<<*y<<endl;
  passPointers(y);
      
  //cout<<"y is "<<y<<" *y is "<<*y<<endl;//line a
  cout<<" *y is "<<*y<<endl;//It returns 5
  return 0;
}

If I uncomment line a, it returns address of y , *y returns some unknown integer value.Am I breaking some norms of C++. I used this link while writing this code. I am using g++ 7.3.0

Community
  • 1
  • 1
motiur
  • 1,640
  • 9
  • 33
  • 61
  • 7
    `p` is destroyed immediately after execution leaves `passPointers()`. Thus the pointer becomes dangling, and reading the pointed value gives you undefined behavior. – HolyBlackCat Jan 14 '19 at 15:12
  • 2
    You're returning the address of a local variable. That variable does not exist outside of that function, and accessing it is undefined behavior. – Retired Ninja Jan 14 '19 at 15:12

1 Answers1

5
void passPointers(int* &a){
    int p = 5;
    a = &p;
} // p dies here

The pointer becomes dangling because you're binding it to the address of a local variable.

Andreas DM
  • 10,685
  • 6
  • 35
  • 62