I've recently been reading the C standard ISO/IEC 9899:2018 specification. Wherein, Section 6.5.6 (Additive operators) describes constraints on the + operator. Rule [8] says:
When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integer expression. In other words, if the expression P points to the i-th element of an array object, the expressions (P)+N (equivalently, N+(P)) and (P)-N (where N has the value n) point to, respectively, the i + n-th and i − n-th elements of the array object, provided they exist. Moreover, if the expression P points to the last element of an array object, the expression (P)+1 points one past the last element of the array object, and if the expression Q points one past the last element of an array object, the expression (Q)-1 points to the last element of the array object. 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. If the result points one past the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated.
Apart from the behaviour of arithmetic on arrays, I've also understood this rule as also describing that since null pointers don't point to any objects arithmetic on them is undefined behaviour. (A Reddit post I've found in relation to this supports my conclusion)
Firstly: Is my comprehension of the above statement correct?
Secondly: What about the code below? Will that also be considered UB, if so/if not, why? Do the rules described in Section 6.5.6 also apply to intptr_t? The above code also doesn't seem to violate the rules in Section 6.3.2.3 (Pointers).
int arr[2] = {0};
intptr_t ptr_0 = 0;
intptr_t ptr = (intptr_t) arr;
intptr_t new = ptr_0 + ptr;
int* ptr_int = (int*) new;
Some other sections that provide more context:
- Section 6.3.2.3 (Pointers) - Rules [1-6]
- Section 6.3.2.2 (Void)
- Section 6.2.5 (Types) - Rules [1,19,20,28]
Thanks for your help in advance!
intptr_tis not a pointer, it's an integer. The rules for pointer addition are irrelevant.intptr_tis a signed integer. So adding two values that cause overflow is undefined.newis identical toptr, so the code snippet is well-defined, butptr_0does not necessarily correspond to a null pointer.