Skip to content

Lifetime and Read-only Access

The Course
•
32 min study

A pointer is only an address. It does not keep the object at that address alive, and it does not know when the object is gone. If a function creates a local variable and hands its address back to the caller, the variable is destroyed as the function returns, and the caller is left holding a dangling pointer: an address where nothing valid lives any more. Using it is undefined behavior, and it is one of the classic C bugs, because the program often seems to work until some unrelated change makes it fail. This lesson gives you two questions to ask about every pointer: how long does its target live, and who is allowed to change it?

Predict and run

Predict before running C
#include <stdio.h>

void show(const int *value) {
    if (value != NULL) {
        printf("%d\n", *value);
    }
}

int main(void) {
    int minutes = 20;
    show(&minutes);
    minutes = 30;
    show(&minutes);
    return 0;
}
Check your prediction
Text
20
30

main owns minutes, and it is alive for the whole of main, so both calls receive a valid address. The second call sees 30 because show reads the current value through the pointer each time. const stopped show from changing the value, but it did not stop main.

How long objects live

Every object has a lifetime, the stretch of the run during which it exists and its address is valid.

  • A local variable, including a parameter, lives from the moment its block is entered until the block ends. This is automatic storage.
  • A string literal such as "focus", and any variable declared outside all functions, lives for the whole run. This is static storage.

A pointer to an object is valid only during that object's lifetime. Once the block ends, the object is gone even though its address is still in your pointer.

C
int *make_minutes(void) {
    int minutes = 25;
    return &minutes;
}

minutes dies as make_minutes returns, so the caller receives a dangling pointer. The compiler can spot this case:

Shell
warning: address of stack memory associated with local variable 'minutes' returned [-Wreturn-stack-address]

It cannot spot every case. A pointer saved into a variable and used after the block ends is just as wrong, and often produces no warning:

C
int *saved = NULL;
{
    int temporary = 40;
    saved = &temporary;
}
printf("%d\n", *saved);

That read may print 40, because the memory has not been reused yet. That is luck, not correctness, and a different compiler setting can change the result.

Return values, or let the caller provide storage

There are two safe ways to give a result back. Return the value itself, which is copied out before the local dies. Or let the caller own the storage and pass its address in, as set_minutes did in the last lesson: the caller's variable outlives the call, so writing through the pointer is safe. In both cases you can say who owns every object and that it outlives every pointer to it. This course never needs dynamically allocated memory; when you meet it later, the same ownership question applies with more ways to get the answer wrong.

const limits the pointer, not the object

const int *value means "through this pointer, you may read the int but not change it". An assignment such as *value = 0; is a compile error:

Shell
error: read-only variable is not assignable

It is a promise made by the function to its caller, visible in the declaration. It does not make the object permanently constant: the owner, main above, still changes it freely. A string literal is the opposite case. Its characters must never be modified, so a pointer to one should be const char *, and the compiler will then reject any attempt to write through it.

Static text outlives the function C
#include <stdio.h>

const char *size_name(int minutes) {
    if (minutes >= 60) {
        return "long";
    }
    return "short";
}

int main(void) {
    const char *name = size_name(90);
    printf("%s %s\n", name, size_name(20));
    return 0;
}
Text
long short

Returning a pointer is safe here because the literals have static storage: they exist for the whole run, so the pointer never dangles.

Practice

Exercise

Your turn

Write two functions. const char *label_for(int minutes) returns "invalid" outside 1 through 180, "short" below 25 and "focus" otherwise. int read_or_zero(const int *value) returns the pointed-to value, or 0 when given NULL. Print:

Text
25: focus
5: short
0: invalid
Read: 12 0

The last line reads a live int holding 12, then NULL.

Your workspace C
#include <stdio.h>

int main(void) {
    // Write your solution here.
    return 0;
}
Hint 1: the idea

Returning a string literal is safe because it lives for the whole run. Reading through a pointer is safe only after you know it is not NULL, and only while its target is alive.

Hint 2: a first step

Start read_or_zero with if (value == NULL) { return 0; }. Keep the int holding 12 in main, so it stays alive during the call.

Show one solution
C
#include <stdio.h>

const char *label_for(int minutes) {
    if (minutes < 1 || minutes > 180) {
        return "invalid";
    }
    if (minutes < 25) {
        return "short";
    }
    return "focus";
}

int read_or_zero(const int *value) {
    if (value == NULL) {
        return 0;
    }
    return *value;
}

int main(void) {
    printf("25: %s\n", label_for(25));
    printf("5: %s\n", label_for(5));
    printf("0: %s\n", label_for(0));
    int minutes = 12;
    printf("Read: %d %d\n", read_or_zero(&minutes), read_or_zero(NULL));
    return 0;
}
Text
25: focus
5: short
0: invalid
Read: 12 0

Every pointer in this program points at something alive: three literals with static storage and one local owned by main, which outlives the call. The NULL check means the function never dereferences a pointer with no target. In the checkpoint you will group related fields into a record and update it through a pointer.

Was this article helpful?

Your response is saved on this device.