What is the relation between the scope and the lifetime of a variable?
As Oli stated, variables have scope and objects lifetime. The scope of a variable and the lifetime of it are bound, but you can have objects whose lifetime extends beyond the scope on which they were created:
int* f() {
int *p // Variable p
= new int(1); // object (call it x)
return p; // p scope ends, p lifetime ends, x survives
}
int main() {
int *q // Variable q
= f(); // ... points to x
delete q; // x lifetime ends, q is in scope, q is alive
}
In your particular case, x
variable ends it's lifetime when the scope in which it was created is closed, so you have undefined behavior.
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.
This is a detail of implementation. Accessing the variable is undefined behavior in all cases and because not all cases must be equal, and if the variable had a non trivial destructor, it would be called at the end of the scope, so whether the memory is there or not is irrelevant: the object is no longer there. That being said, in many cases compilers will not release the memory in the function (i.e. they will not reseat the frame pointer) when a variable goes out of scope, but they might reuse the same space to hold other variables in the same function.