0

Let's say we have:

struct A
{
    int data;
};

int main( void )
{
  {
    A a;
    a.data = 4;
  }

  cout << "Hello World" << endl;
  return 0;
}

I understand that object created without new is stored on the stack and is destructed automatically upon exit from the scope in which it is defined. So by the time it gets to execute line 13 the object a should not exist.

The second case:

struct A
{
    int data;
};

int main( void )
{
 A * b;
  {
    A a;
    a.data = 4;
    b = &a;
  }

  cout << b->data << endl;
  return 0;
}

The question is when will be the object destroyed if I assign the address of a inside the scope to a pointer? Since I can print the data value of that object outside of the scope that means the object must still exist.

  • 2
    Nothing is different. It's just that your code is broken, because it accesses an object that doesn't exist anymore. – Kerrek SB Sep 22 '17 at 15:13
  • `b` becomes a so-called 'dangling pointer'. – alain Sep 22 '17 at 15:14
  • You should read [this very nice explanation](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope). After, you'll understand why you still can print the data of the object outside the scope. – Jabberwocky Sep 22 '17 at 15:29

1 Answers1

3

No, it means that you have encountered undefined behavior so any conclusion that you could deduce is irrelevant.

The address stored in b won't point to any valid data after closing the scope, period.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • 2
    Please close as a dupe instead of answering – NathanOliver Sep 22 '17 at 15:13
  • 1
    @NathanOliver I mark it for closing but for such simple questions I also answer, especially if the OP is new so that he also can get what he asked for. – Jack Sep 22 '17 at 15:15
  • Answering these questions only encourages posting more of the same. – Sam Varshavchik Sep 22 '17 at 15:21
  • @SamVarshavchik: any statistical proof of this or you are just assuming that users are not able to learn how to search things? Because in that case they won't care to search at all in any case. – Jack Sep 22 '17 at 15:21
  • Just stick around, and keep refreshing the C++ tag. Proof should be coming up before too long. – Sam Varshavchik Sep 22 '17 at 15:23
  • @SamVarshavchik: what I mean is: do you have any proof that just closing a question for duplicate OR closing a question for duplicate and answering it when it's simple question reduces the amount of duplicate questions? I'm on the opposite side: the average user won't read a wall of text regarding a question like this because he doesn't want to, so providing a simple answer may help in reducing the amount of the same question. – Jack Sep 22 '17 at 15:26