Pointer arithmetics with two different buffers
Consider the following code:
int* p1 = new int[100];
int* p2 = new int[100];
const ptrdiff_t ptrDiff = p1 - p2;
int* p1_42 = &(p1[42]);
int* p2_42 = p1_42 + ptrDiff;
Now, does the Standard guarantee that p2_42
points to p2[42]
? If not, is it always true on Windows, Linux or webassembly heap?
To add the standard quote:
expr.add#5
When two pointer expressions
P
andQ
are subtracted, the type of the result is an implementation-defined signed integral type; this type shall be the same type that is defined asstd::ptrdiff_t
in the<cstddef>
header ([support.types]).
(5.1) If
P
andQ
both evaluate to null pointer values, the result is 0.(5.2) Otherwise, if
P
andQ
point to, respectively, elementsx[i]
andx[j]
of the same array objectx
, the expressionP - Q
has the valuei−j
.(5.3) Otherwise, the behavior is undefined. [ Note: If the value
i−j
is not in the range of representable values of typestd::ptrdiff_t
, the behavior is undefined. — end note ]
(5.1) does not apply as the pointers are not nullptrs. (5.2) does not apply because the pointers are not into the same array. So, we are left with (5.3) - UB.
const ptrdiff_t ptrDiff = p1 - p2;
This is undefined behavior. Subtraction between two pointers is well defined only if they point to elements in the same array. ([expr.add] ¶5.3).
When two pointer expressions
P
andQ
are subtracted, the type of the result is an implementation-defined signed integral type; this type shall be the same type that is defined asstd::ptrdiff_t
in the<cstddef>
header ([support.types]).
- If
P
andQ
both evaluate to null pointer values, the result is 0.- Otherwise, if P and Q point to, respectively, elements
x[i]
andx[j]
of the same array objectx
, the expressionP - Q
has the valuei−j
.- Otherwise, the behavior is undefined
And even if there was some hypothetical way to obtain this value in a legal way, even that summation is illegal, as even a pointer+integer summation is restricted to stay inside the boundaries of the array ([expr.add] ¶4.2)
When an expression
J
that has integral type is added to or subtracted from an expressionP
of pointer type, the result has the type ofP
.
- If
P
evaluates to a null pointer value andJ
evaluates to 0, the result is a null pointer value.- Otherwise, if
P
points to elementx[i]
of an array objectx
with n elements,81 the expressionsP + J
andJ + P
(whereJ
has the valuej
) point to the (possibly-hypothetical) elementx[i+j]
if0≤i+j≤n
and the expressionP - J
points to the (possibly-hypothetical) elementx[i−j]
if0≤i−j≤n
.- Otherwise, the behavior is undefined.