Pointers & Memory · advanced · ~8 min
Distinguish an out-of-bounds pointer from a pointer whose target has expired.
A dangling pointer refers to an object whose lifetime has ended. This can happen after free or after leaving the block of an automatic local object. Being inside a numeric address range is not enough: the object must also still be alive.
A function must not return the address of its automatic local variable for later use. To return data safely, return a value, fill caller-owned storage, or return a new owned allocation with documented cleanup.
A pointer into a live array is borrowed. Check an index before forming the element pointer, and keep the source object alive while using the result. Bounds and lifetime are independent checks: an in-range index cannot rescue a freed source.
The linked exercises practice bounds checking as one part of pointer validity. They do not detect expired objects or prove general memory safety.
A dangling pointer refers to an object whose lifetime has ended. This can happen after free or after leaving the block of an automatic local object. Being inside a numeric address range is not enough: the object must also still be alive.
#include <stdio.h>
void make_value(int *out) { *out = 8; }
int main(void) {
int result = 0;
make_value(&result);
printf("%d\n", result);
return 0;
}
Expected output on a successful allocation, where applicable:
8
The caller owns result and keeps it alive while make_value writes to it. No pointer to a callee-local variable escapes its block.
&local from a function cannot replace this output-parameter approach.Check lifetime as well as bounds. A returned borrowed pointer requires a live owner. Prefer returning values or writing caller-owned storage when an allocation is unnecessary.