simpleroseinc

Logo

Developer Tips

View Company GitHub Profile

1 February 2021

Invalid pointer values

by Zhihao Yuan

J official implementation, by default, keeps an integer that represents a pointer to a local variable in function JInit:

double y;
jt->cstackinit=(uintptr_t)&y;

After the function exits, it is legal to use jt->cstackinit in arithmetic expressions, but it would not be legal to cast this integer back to double*. Without the (uintptr_t) cast, it is not legal to do pointer arithmetic around the dangling pointer either.

In C++, only three kinds of pointer values are valid:

  1. A pointer to an object (whether or not the object’s lifetime has ended) or a function, or
  2. a past-the-end pointer, or
  3. a null pointer.

Example for the past-the-end pointers:

int a;
auto p = &a + 1;  // ok
int b[2];
auto pe = b + 2;  // ok

All other pointer values are invalid pointer values. Typically, when a pointer refers to a storage region that reached its end of the duration, that pointer has an invalid pointer value. An implementation has the right to terminate the program when you attempt to copy an invalid pointer value, regardless of whether you attempted to dereference that pointer.

tags: cplusplus - safety