A valid pointer is a pointer value that refers to an object of its designated type or to the first element of an array of that type. Pointer arithmetic can produce pointers to later array elements and to the first position beyond the array; the one-past value is valid for comparison but does not designate an object for dereferencing. section 11.1.2 section 11.1.4
Use these rules to keep pointer state and operations valid:
- Initialize pointers explicitly; use null when no valid address is available. section 11.1.4 section 6.2
- Treat a pointer’s truth value as a null test, not as proof that the pointer is valid; invalid pointers are not safely distinguishable this way. section 11.1.4 section 6.2
- Dereference only an object of the pointer’s designated type; accessing a non-value representation or a non-object through the pointer fails. section 11.1.4
- Keep pointer arithmetic within an array’s range or at its one-past position; adding beyond that position is invalid. section 11.1.4
Array traversal and the one-past pointer
For double A[2] = { 0.0, 1.0, }, p = &A[0] starts valid and dereferences A[0]. After ++p, it remains valid and dereferences A[1]. After a second ++p, it is still a valid pointer value, but it points beyond the array and must not be dereferenced. Advancing once more with p += 3 from A[0] performs invalid pointer addition. section 11.1.4
double sum2(size_t len, double const* a) {
double ret = 0.0;
for (double const*const aStop = a+len; a < aStop; ++a) {
ret += *a;
}
return ret;
}
Compare a pointer against the one-past position while summing an array, without dereferencing that endpoint. section 11.1.2
