In this code, I reference the local variable b
even though it is out of scope. But I do it from within the same function so it's probably still on the stack, right? I ran the program and it worked but I'd like to know if it's guaranteed to work on all implementations.
#include <iostream>
void main()
{
int* a;
{
int b = 5;
a = &b;
}
std::cout << *a;
}
No, that's not guaranteed to work. a
is dangling once the inner scope is exited, so any dereference of it results in Undefined Behaviour and nothing whatsoever is guaranteed.
The problem here is not that b
is out of scope. It is that the lifetime of b
has ended. Scope is about where the name of an object is known. Lifetime is about when the object exists (within the computational model).
Technically, the object b
does not exist when you reference it with *a
. The bytes that were used to represent it might happen to be still unchanged in memory, and accessing them with *a
might happen to work sometimes, especially if optimization is not turned on, but it is undefined behavior.
An object can still be accessible even though its name is not in scope. Here is an example of an object that is accessible during its lifetime even though it is not in scope:
void foo(void)
{
int b;
bar(&b);
}
In this code, the function bar
may access b
, even though it cannot see the name of b
in foo
. Although control leaves the block in which b
is created, execution of the block is merely suspended, not terminated. So b
continues to exist even while the function bar
is executing. So b
will be out of scope, but the access will be during its lifetime.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With