liveBook · Manning

Valid pointer

As explained in Modern C, Third Edition

A valid pointer is a pointer value whose state permits the pointer operations defined by the C language.

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

How Modern C, Third Edition covers it

How deep it goes
Defines valid, null, and invalid states, then works through array bounds, designated types, non-value representations, and one-past behavior.
Examples
Demonstrates array summation, pointer walking, null tests, one-past values, invalid addition, and dereferencing beyond an array.
What it assumes
Assumes familiarity with pointers and objects while establishing their relationship to arrays, null values, and pointer initialization.
What you can do after
Diagnose pointer states and avoid invalid dereferences or out-of-range pointer arithmetic in array-oriented C code.
How it connects
Connects pointer validity with arrays, pointer arithmetic, null pointers, dereferencing, type systems, and undefined behavior.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.