Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean for a pointer to point to a location just immediately past the end of an object?

Tags:

c++

pointers

What does it mean for a pointer to point to a location just immediately past the end of an object?

From C++ Primer, pg 52:

Pointer Value

The value (i.e., the address) stored in a pointer can be in one of four states:

  1. It can point to an object.
  2. It can point to the location just immediately past the end of an object.
  3. It can be a null pointer, indicating that it is not bound to any object.
  4. It can be invalid; values other than the preceding three are invalid.
like image 520
user3371648 Avatar asked Nov 16 '25 06:11

user3371648


2 Answers

A pointer immediately past the end of an object is a pointer whose address is offset from that of the object by exactly sizeof object.

Since pointer arithmetic already considers the type of the object:

T object;
T *past = &object + 1; // 1 is sizeof object

Or doing manual arithmetic:

T object;
char *past = reinterpret_cast<char*>(&object) + sizeof object;

Although in the second case, due to the difference in types it would be trickier to use the pointer correctly.

like image 83
David Rodríguez - dribeas Avatar answered Nov 17 '25 21:11

David Rodríguez - dribeas


"Past the end of an object" becomes more interesting in the context of arrays.

Suppose you have a two element array: int arr[2] = {1, 2}

Based on arr you can compute these pointers: int * p1 = arr int * p2 = arr + 1 int * p3 = arr + 2

You can dereference p1 and p2, but attempting to do the same to p3 invokes undefined behavior. Also, any pointer arithmetic based on arr that results in another pointer than the three mentioned above means UB.

So, the only things you can do with p3 are:

  • subtracting values (leading to either the values of p1 or p2)
  • compare it with another pointer (if p3 == arr + 2)

As for reasons why it should be considered valid, consider an usual way to use iterators:

for (container::iterator iter = myContainer.start(); iter != myContainer.end(); ++iter)

Here, myContainer.end() might be just a pointer to an element just past the end (of an array). It would be a shame if it wasn't a valid pointer and the whole construct were UB.

like image 43
Andrei Avatar answered Nov 17 '25 19:11

Andrei