Pointers and object lifetime

Lesson 4 of 14 · C memory foundations

An object occupies storage during its lifetime. An address identifies a location in a program’s address space. On systems with virtual memory, that address is generally a process-specific virtual address, not a promise about a physical RAM location. The abstract C model does not require every object to occupy a visible hardware address at all times.

#include <stdio.h>
int main(void) {
    int score = 4;
    int *p = &score;
    *p = 9;
    printf("%d\n", score);
    return 0;
}

Output is 9. &score obtains the address; int *p declares a pointer to int; *p accesses the pointed-to integer. The pointer is itself an object, distinct from its target:

p [ address of score ] ───> score [ 4 ]
                                      write *p = 9
                              score [ 9 ]

An initialized null pointer (int *p = NULL;, with <stddef.h>) points to no object and must not be dereferenced. An uninitialized pointer, an out-of-bounds pointer, or a pointer to an object whose lifetime ended is not safe to dereference. Undefined behavior means C imposes no requirements on what happens; a crash is not guaranteed.

A local object declared inside a block normally has automatic storage duration: its lifetime ends when execution leaves the block. A pointer to that object cannot safely provide access after that. static local objects instead have static storage duration and retain their value across calls. Scope, where a name is visible, is distinct from lifetime, when its object exists. A function may return a small struct by value instead of returning the address of a local object.

Chapter index · Course index