-1

Imagine we have a scope where a variable is defined and a pointer with larger scope gets this variable's reference. What happens when we leave the scope knowing that the pointer is defined in the outer scope, a class member for example.

   {
       int a = 6;
       pointa = &a; //defined out of this scope
   }
   //what happens here, pointa is still defined in this scope

EDIT: My question was concerning a more specific case which I cannot find an answer to (it feels like the answer lies within the dangling pointer explanation though).

Suppose foo() is a function that returns a double. I tried this:

    int* p;
    p = &foo();  

But then p becomes empty. Can you please explain how this relates to a dangling pointer?

hamza keurti
  • 385
  • 1
  • 2
  • 15

1 Answers1

0

What happens when we leave the scope knowing that the pointer is defined in the outer scope, a class member for example.

The pointer becomes a dangling pointer.

Dereferencing it to access the object's members, member variables as well as member functions, will lead to undefined behavior.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
R Sahu
  • 204,454
  • 14
  • 159
  • 270