-2

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
  • 345
  • 2
  • 13

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
  • 111,130
  • 12
  • 123
  • 212
R Sahu
  • 200,579
  • 13
  • 144
  • 260