22

The C++ standard [sec 5.7] says:

If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

So, am I correct in assuming that pointers one-past-the-end of other types than arrays are undefined?

For example:

int a = 0;
vector<int> v(&a, (&a)+1);

The above snippet compiles and works just fine (with g++), but is it valid?

Bernhard Kausler
  • 5,119
  • 3
  • 32
  • 36
  • I would like to comment about whether `pointers one-past-the-end of other types than arrays are undefined?`. **Pointers** are always defined, since they are simply numbers, addresses. The **value** by this pointer is undefined however. You must not dereference these pointers. But `vector` constructor doesn't dereference them, so it's ok. – NIA Jan 24 '13 at 16:26
  • True, but the address space is not infinite. So there is a pointer to the very last element in address space. Incrementing that pointer would make no sense. – Bernhard Kausler Jan 24 '13 at 16:28
  • 7
    Pointers are not simply numbers. The C++ standard makes it very clear that you can't use arbitrary addition and subtraction with pointers. In particular the practice to use a pointer to one before an array to accommodate 1-based algorithms causes undefined behavior. AFAIK there are or used to be computer architectures, where loading a value that does not point to valid memory into a pointer register could cause a trap. – JoergB Jan 24 '13 at 16:33
  • 2
    "Pointers are always defined, since they are simply numbers, addresses." -- Utterly wrong. Ever hear of a segment register? – Jim Balter Jul 21 '14 at 09:41
  • @LightnessRacesinOrbit and others, OK, I sincerely admit defeat :) Sorry. It was over-simplified/over-generalized statement. And of course I would not recommend such practice as in snippet above for regular use (especially because since c++11 we can initialize vectors of a few items with initializer lists). – NIA Jan 24 '17 at 13:29

1 Answers1

28

No, it is legal. 5.7(4) - one paragraph before your quote - says: "For the purposes of these operators, a pointer to a nonarray object behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type."

JoergB
  • 4,383
  • 21
  • 19