Scope, lifetime, and storage duration
Separate where a name is visible from when an object exists, then connect those rules to safe pointer use.
In this chapter10 sections
A name can disappear from view while its object still exists. An object can also stop existing while a pointer still holds an unusable old value. Scope and lifetime explain these different situations.
Need the ideas side by side? Open the concept guide.
1. Three questions, three concepts
| Question | Concept | What it describes |
|---|---|---|
| Where can I use this name? | Scope | A region of program text. |
| When does this object exist? | Lifetime | A period during execution. |
| Can declarations refer to the same entity? | Linkage | Relationships between declarations. |
Scope is about identifiers, not a physical memory region. Lifetime is about objects, not whether a name is currently visible. Linkage answers a third question and is neither the amount of memory nor the duration of a function call. The same keyword, such as static, can affect different things in different contexts.
2. A hidden name does not erase an object
Here assert is a check from <assert.h>. With assertions enabled, a false condition reports failure and aborts; it does not make an invalid operation safe. This fragment belongs inside a function.
int score = 4;
{
int score = 9;
assert(score == 9);
}
The inner declaration introduces another object and hides the outer identifier within that inner scope. It does not overwrite the outer object. After the inner block, the outer name is visible again and its value remains 4. This is shadowing. Using distinct names is usually easier for a beginner to follow, but the example reveals why a name and an object must be kept separate.
3. Storage duration groups lifetime rules
Storage duration has four categories: automatic, static, thread, and allocated. For a non-VLA automatic object, its lifetime generally extends from entry into its associated block until that block’s execution ends. Initialization and name visibility still have their own positions in the source text. A variable-length array has a different lifetime start: its declaration. Each recursive entry has its own automatic instances.
Static-storage objects exist for the entire program execution. Thread-storage objects have lifetimes tied to the corresponding thread; later concurrency material explains the access rules. Allocated objects have lifetimes controlled through allocation and deallocation. These categories do not require the hardware regions called stack, data segment, or heap.
4. Local visibility can coexist with a long lifetime
#include <assert.h>
static int next_count(void)
{
static int count = 0;
count += 1;
return count;
}
int main(void)
{
assert(next_count() == 1);
assert(next_count() == 2);
return 0;
}
The identifier count is visible only in its block, yet the object retains its value across these two calls. Its initializer is not reapplied on every entry. The identifier of a block-scope static object has no linkage; a file-scope static function name, as used for next_count, has internal linkage. These are separate effects of static in separate declarations.
5. A pointer does not extend a target’s lifetime
The following is a small preview of pointer notation: &total points to total, and *view accesses it. The next lesson develops that notation; here, follow which object stays alive.
int total = 4;
{
int *view = &total;
*view = 7;
}
Here the outer object remains alive while the inner pointer is used. The pointer’s own block ends first, which is fine. Reversing the relationship would be dangerous: storing the address of an ordinary local object somewhere longer-lived does not keep the local object alive. Returning its address does not create a lasting object either.
When an object’s lifetime ends, pointers to it or just past it become indeterminate under the C17 rule. Do not dereference, print, compare, or otherwise rely on a stale pointer value. You may assign a fresh valid value or a null pointer to the still-live pointer object without reading the old value. This resets that one pointer; it does not repair other aliases.
Primary references and further reading
- WG14 N1570 — public C11 committee draft: 6.2.1, 6.2.2, 6.2.4. These stable rules support the C17 baseline; this draft is not the final ISO publication.
Optional visual model: Separate visibility from lifetime
Separate visibility from lifetime
VISUAL MODEL
Follow an inner block containing an ordinary local and a static local. Track names and objects separately.
The inner block is inside a running function. local is a non-VLA automatic int. kept has static storage duration and is initialized before program startup.
/* inside a function, before the inner block */{static int kept = 2;int local = 3;/* both names are visible here */}/* outside the inner block */
kept2Alive; name out of scopelocal—Lifetime not begun; name hiddenBefore entering the inner block, kept is alive but its name is not in scope here. local’s lifetime has not begun.
Scope answers where a name is visible. Lifetime answers when an object exists. An ordinary non-VLA automatic object’s lifetime begins at block entry, before its initializer is reached.
Read the complete trace
- Before entering the inner block, kept is alive but its name is not in scope here. local’s lifetime has not begun.
- Entering the block begins local’s lifetime. Its name has not been declared here yet, and its initializer has not run.
- kept’s declaration brings its name into scope. It already holds 2; entering the block does not reinitialize it.
- local’s declaration makes the name visible, and its initializer stores 3. Both objects are alive.
- Here both names are visible and both objects are alive. These are separate properties.
- Leaving the block ends local’s lifetime. kept remains alive, but both names are outside their scope here.
- kept still exists with value 2. This model describes its state; code here cannot use that out-of-scope name directly.
Where a name is visible and when an object exists
Compare, follow, and explain this idea
Scope describes where an identifier can be used in source code. Lifetime describes when an object exists during execution. Storage duration supplies rules that determine that lifetime.
When this helps Use these questions when reading blocks, local static objects, recursion, and pointers that escape a function.
Read the ideas side by side
- Scope
- A source-code region in which a particular name can refer to its declared entity.
- Lifetime
- A period of execution in which an object exists and its storage is reserved.
A hidden name does not necessarily mean a dead object.
- Automatic local fresh
- A new object exists for each active call here. Its initializer supplies 0 when reached.
- Static local total
- One object lasts for the whole program and keeps its stored value between calls.
Both names have block scope; their objects have different storage durations.
- Name and initializer
- For fresh, scope begins just after its declarator in source. Its automatic initializer runs each time execution reaches the declaration.
- Entering a block
- For an ordinary non-VLA automatic object, lifetime begins on entry to its associated block.
Do not treat name visibility, lifetime start, and initialization as one event.
Follow the reasoning
Call visit twice in separate statements. The returned number puts total in the tens position and fresh in the units position.
C17 · illustrative fragments in the stated context
int visit(void) {static int total;int fresh = 0;++total;++fresh;return total * 10 + fresh;}
- Before the calls
The static object total already exists and is zero-initialized before program startup. Its name is only visible in its declared block.
- Start the first call
A fresh automatic object belongs to this call. When its declaration is reached, its initializer stores 0.
- Increment and return
total becomes 1 and fresh becomes 1. The function returns 11; that call’s fresh object ends when its block is left.
- Start the second call
The same total object still holds 1. A new fresh object is initialized to 0 for this call.
- Increment again
total becomes 2 and the new fresh becomes 1. The second result is 21. The two automatic objects never need to exist together here.
Common misconceptions
These statements are misleading. Open each one to see why.
MisconceptionAll local objects are created when their declaration line executes.
For ordinary non-VLA automatic objects, lifetime begins at block entry; the declaration can introduce the name and run initialization later. VLAs have different lifetime rules.
MisconceptionA local static object is created anew on every call.
The name has local scope, but the object has static storage duration. In this C example, initialization is not a C++-style first-call operation.
MisconceptionReturning a pointer extends a local object’s lifetime.
Returning a pointer value does not extend the pointed-to object’s lifetime. Do not access an ordinary local object after its function has returned.
Go a little deeperOptional technical detail
Scope is about identifiers
Objects can still be reached through valid pointers even when their own names are out of scope. An object’s lifetime must independently permit that access.
Avoid turning a model into a machine promise
“Stack local” is useful implementation vocabulary, not the C definition of automatic storage duration. C does not mandate one physical stack layout for these objects.
C17 The walkthrough uses ordinary automatic int objects and one zero-initialized static int. It excludes VLAs, longjmp, threads, and compound-literal lifetime details.
C23 The scope/lifetime distinction still applies in C23. New syntax does not make a pointer to an expired automatic object valid.
Public committee drafts; clause references help you verify the explanation. N3096 is a C23 working draft.
Say it in your own words
Why does fresh return to 0 for the second call while total keeps 1?
Compare with an explanation
The second call has a new automatic fresh object whose initializer stores 0. The static total object continues to exist between calls.
Before you move on
- Scope describes name visibility; lifetime describes when an object exists.
- Storage duration determines lifetime rules rather than one universal stack diagram.
- A pointer cannot extend a target object’s lifetime merely by retaining its address.
Keep these ideas separate
- Name unavailable / Object no longer alive
- A name can leave scope while a static object persists; an ended target lifetime makes stale pointer use a different problem.
Why can returning an address of an ordinary automatic local object leave the caller without a usable target?
Optional: say it aloud or keep a note. You can continue whenever you are ready.Check your understanding
Optional. Answers are not saved or sent, and reading stays unrestricted.
Read the explanation for every choice
- Its object remains alive, while that name is outside its block scope here.
✓ Correct reasoning. Static storage duration and block scope answer different questions.
- Its object must be destroyed at block exit.
That describes ordinary automatic storage, not a static local’s storage duration.
- Its name becomes globally visible.
Static storage duration does not turn a block-scope identifier into a file-scope identifier.
C17
Ready for the next idea?
Mark this chapter as read whenever you feel ready.