Search code examples
clanguage-lawyerpointer-arithmetic

Pointer to one-before-first element of array is UB. When was this first defined so?


Decrementing a pointer to the first element of an array is an undefined behaviour as of C17. This answer cites C17 standard saying

C17 6.5.6/8

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.

Is this the earliest standard where this was defined? How such operation was defined in earlier standards? Was it legal before?


Solution

  • The very earliest C standard, C89, has the same rule in 3.3.6 Additive Operators:

    When an expression that has integral type is added to or subtracted from a pointer, the integral value is first multiplied by the size of the object pointed to. The result has the type of the pointer operand. If the pointer operand points to a member of an array object, and the array object is large enough, the result points to a member of the same array object, appropriately offset from the original member. Thus if P points to a member of an array object, the expression P+1 points to the next member of the array object. Unless both the pointer operand and the result point to a member of the same array object, or one past the last member of the array object, the behavior is undefined. Unless both the pointer operand and the result point to a member of the same array object, or the pointer operand points one past the last member of an array object and the result points to a member of the same array object, the behavior is undefined if the result is used as the operand of a unary * operator.

    I don't believe that forming pointers to the "-1" element of an array has ever been well-defined C. Of course there might have been specific implementations where it happened to work, or was documented to do so.