Null, Validity, and Lifetime
No shelf selected
NULL is a useful value when no object has been selected. If a pointer might be null, check it before dereferencing: *pointer cannot be used when pointer == NULL. A nonnull pointer is not automatically safe, though. An address of a local variable cannot be used once that variable's lifetime has ended, so do not return such an address from a function.
#include <stdio.h>
int main(void) {
int shelf = 12;
int *selected = NULL;
if (selected == NULL) {
printf("No shelf selected\n");
}
selected = &shelf;
if (selected != NULL) {
printf("Shelf: %d\n", *selected);
}
return 0;
}
The first branch prints a message without dereferencing selected. Once selected = &shelf runs, the pointer reaches a live integer, so the second branch can read 12. NULL is available from <stdio.h> here; it represents a null pointer, not an integer object whose value happens to be zero.
Returning a value versus returning a local address
This separate illustration follows a helper that returns the value 7; it is not a trace of the shelf example above.
The add_fee example earlier returned an integer value. That result remains usable after the helper ends. Returning the address of an ordinary local variable would be different: the caller would have no live object to read through that address. Such a stale pointer is often called dangling. Do not dereference it, print it, or compare it with NULL to test whether it is safe. An object's lifetime ending does not automatically reset other pointers to NULL.
Scope and lifetime remain separate. A helper cannot name main's shelf directly, but a valid pointer can reach it while main waits. Conversely, a pointer name can still be in scope after its target object's lifetime has ended.
Later, allocated-memory lessons introduce objects whose lifetime is managed explicitly. That storage is often called the heap; it is separate from the conceptual call stack. For now, use addresses of objects you know are still alive. All runnable examples here avoid expired objects.