What is the relation between the scope and the lifetime of a variable?
If a variable is out of scope, is the memory of it allowed to be overwritten by another variable, or is the space reserved until the function is left.
I am aksing because I want to know whether the code below actually works, or whether it can be that *p might be undefined
foo() {
int *p;
{
int x = 5;
p = &x;
}
int y = *p;
}
Scope is the region or section of code where a variable can be accessed.
Lifetime is the time duration where an object/variable is in a valid state.
For, Automatic/Local non-static variables
Lifetimeis limited to theirScope.In other words, automatic variables are automagically destroyed once the scope(
{,}) in which they are created ends. Hence the name automatic to begin with.So Yes your code has an Undefined Behavior.
In your example scope of
*pis entire function body after it was created.However,
xis a non-static local/automatic variable and hence the lifetime ofxends with it’s scope i.e the closing brace of}in which it was created, once the scope endsxdoes not exist.*ppoints to something that doesn’t exist anymore.Note that technically
xdoes not exist beyond its scope however it might happen that the compiler did not remove the contents ofxand one might be able to access contents ofxbeyond its scope through a pointer(as you do).However, a code which does this is not a valid C++ code. It is a code which invokes Undefined Behaviour. Which means anything can happen(you might even see value ofxbeing intact) and one should not expect observable behaviors from such a code.