-2

This is the code that I have a question about:

int* getPtrToFive() {   
   int x = 5;   
   return &x;
}  
int main() {   
   int *p = getPtrToFive();   
   cout << *p << endl; // ??? 
}

The lecture slides say that *p wouldn't give a valid result because as getPtrToFive is returned, x goes out of scope. However, I thought that getPtrToFive would already contain the value of 5, which would validate *p? Is it because of the pointer trying to direct me to getPtrToFive which has an out of scope x?

blueyfooey
  • 11
  • 4

2 Answers2

3

You seem to fail to understand the basic concept of a pointer. Think of it as of an address of the house. 1 Main St is your pointer. But what happens, if the house is destroyed? Someone will drive all the way to the 1 Main St, only to find a pile of debris there... Certainly not a good outcome.

So, when the function exits, the house get's destroyed. You still have the address, but there is nothing there left.

SergeyA
  • 61,605
  • 5
  • 78
  • 137
  • Nice analogical example. – Ahmed Akhtar Jun 05 '16 at 02:28
  • I think I'm still not understanding, because that seems contrary to an answer given to another question. http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope The other question showed that even though someone typed up code in the exact same format, they were still able to get a result from cout. Right now, the lecture is saying that you won't get any result, as are you. – blueyfooey Jun 05 '16 at 02:44
  • @blueyfooey, both answers have the same idea in mind. (The one you linked is better than mine, actually). You can get a random result. A random result is just this - random. Might get 5, might get 42, might have a program crash (a variant of random result), or anything else. – SergeyA Jun 05 '16 at 13:14
0

Yes, you are right.

Even if the output is somehow 5, it is illegal to access memory that has been out of scope.

Ahmed Akhtar
  • 1,444
  • 1
  • 16
  • 28