Objc/c++: Can local variable be accessed outside of its scope

http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope

If you push a local variable onto the stack, and return its address. Then in the parent scope, you have a pointer point to the return address.

After the function completes, you dereference the pointer. The result is unstable. …and really depends on whether the system decides to leave your space alone, or have someone else overwrite it.

You rent a hotel room.
You point your pointer to the return address of the local variable

You put a book in the top drawer of the bedside table and go to sleep.
In your local variable, you do stuff with it

You check out the next morning. your function finishes running
… but “forget” to give back your key. You steal the key! You do not point your pointer to NULL

A week later, you return to the hotel, do not check in, sneak into your old room with your stolen key, and look in the drawer. Your book is still there. Astonishing!

Later in your program, you decide to dereference your pointer. Depending on the circumstances, if the system has not over-written the space for that local variable, then you still see your value there! If the system have over-written it, then you will access something that is bizarre and your program may crash.

How can that be? Aren’t the contents of a hotel room drawer inaccessible if you haven’t rented the room?

Well, obviously that scenario can happen in the real world no problem. There is no mysterious force that causes your book to disappear when you are no longer authorized to be in the room. Nor is there a mysterious force that prevents you from entering a room with a stolen key.

The hotel management is not required to remove your book. You didn’t make a contract with them that said that if you leave stuff behind, they’ll shred it for you. If you illegally re-enter your room with a stolen key to get it back, the hotel security staff is not required to catch you sneaking in. You didn’t make a contract with them that said “if I try to sneak back into my room later, you are required to stop me.” Rather, you signed a contract with them that said “I promise not to sneak back into my room later”, a contract which you broke.

In this situation anything can happen. The book can be there — you got lucky. Someone else’s book can be there and yours could be in the hotel’s furnace. Someone could be there right when you come in, tearing your book to pieces. The hotel could have removed the table and book entirely and replaced it with a wardrobe. The entire hotel could be just about to be torn down and replaced with a football stadium, and you are going to die in an explosion while you are sneaking around.

You don’t know what is going to happen; when you checked out of the hotel and stole a key to illegally use later, you gave up the right to live in a predictable, safe world because you chose to break the rules of the system.