Arrays, Pointers and Memory Lifetime
Understand addresses, array boundaries and why returning a pointer to a local variable is a bug.
A pointer is an address on an envelope. It tells you where to look, but does not prove that the object is still there or that you may access it.
An array stores a fixed number of elements contiguously. Valid indexes start at zero and end at length minus one. A pointer can refer to an element, but a raw pointer does not normally carry the array length. Functions processing a buffer therefore need an explicit length or a container or view that retains the size.
Object lifetime matters as much as the address. A local automatic variable usually ceases to exist when its scope ends. Returning its address creates a dangling pointer; using that pointer later is invalid even if the old bytes still seem to be present. Return a value or use caller-owned storage with a documented lifetime.
A null pointer represents no object and must not be dereferenced. A non-null pointer is not automatically valid either: it may point outside an array or into expired storage. Check boundaries before access, and do not attempt to validate arbitrary addresses by simply testing whether they are nonzero.
In C++, std::array keeps fixed-size data and its size together without dynamic allocation. Range-based loops avoid writing an index when it is not needed. In C, an array and a size parameter remain common. In both languages, specify whether a function reads or modifies the data and who owns the storage.
Understand addresses, array boundaries and why returning a pointer to a local variable is a bug.
Core ideas
- Valid indexes are 0 through size − 1.
- An address does not guarantee object lifetime.
- Prefer size-aware interfaces.
Storage bytes = element count × sizeof(element)For 4 elements: valid indexes 0, 1, 2, 3Work through a practical example
1Store four readings: 10, 20, 30 and 40.
2Add them using a range-based loop, producing 100.
3Divide by four using floating arithmetic to obtain 25.0.
4The array remains alive throughout main; no pointer to expired local storage is returned.
Accessing data[length] or returning the address of a local variable.
Code example
C++17 — standalone program; expected output: 25.0
#include <array>
#include <cstdio>
int main() {
const std::array<int, 4> readings{10, 20, 30, 40};
int sum = 0;
for (int value : readings) sum += value;
const double mean = static_cast<double>(sum) / readings.size();
std::printf("%.1f\n", mean);
}Read and run this example in the stated environment. Code is displayed here; it does not execute in your browser.