Scope vs. Lifetime of Variable

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;


}

Solution 1:

What is Scope?

Scope is the region or section of code where a variable can be accessed.

What is a lifetime?

Lifetime is the time duration where an object/variable is in a valid state.

For, Automatic/Local non-static variables Lifetime is limited to their Scope.
In other words, automatic variables are automagically destroyed once the scope({,}) in which they are created ends. Hence the name automatic to begin with.

What is wrong in your code example?

So Yes your code has an Undefined Behavior.

In your example scope of *p is entire function body after it was created.
However, x is a non-static local/automatic variable and hence the lifetime of x ends with it's scope i.e the closing brace of } in which it was created, once the scope ends x does not exist. *p points to something that doesn't exist anymore.

Note that technically x does not exist beyond its scope however it might happen that the compiler did not remove the contents of x and one might be able to access contents of x beyond 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 of x being intact) and one should not expect observable behaviors from such a code.

Solution 2:

C11 Section 6.2.1 Paragraph 2

For each different entity that an identifier designates, the identifier is visible (i.e., can be used) only within a region of program text called its scope. Different entities designated by the same identifier either have different scopes, or are in different name spaces

.

C11 Section 6.2.4 Paragraph 2

The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it.

In your case x is local to the block, and so is its lifetime, therefore x cannot be accessed by its name outside the block, also because its lifetime is limited to its block the address of x will not be reserved anymore after leaving the block, thus will result in undefined behaviour.

On the other hand, for example, say a static local variable, in this case the scope is local to the block and so we can't access by its name outside the block, but the lifetime is the entire program, so we can use the address of the variable anywhere in the program while it is running. This example should help get the difference.