Consider the following code:
int* p1 = new int; int* p2 = new int; const ptrdiff_t ptrDiff = p1 - p2; int* p1_42 = &(p1); int* p2_42 = p1_42 + ptrDiff;
Now, does the Standard guarantee that
p2_42 points to
p2? If not, is it always true on Windows, Linux or webassembly heap?
To add the standard quote:
When two pointer expressions
Qare subtracted, the type of the result is an implementation-defined signed integral type; this type shall be the same type that is defined as
Qboth evaluate to null pointer values, the result is 0.
(5.2) Otherwise, if
Qpoint to, respectively, elements
x[j]of the same array object
x, the expression
P - Qhas the value
(5.3) Otherwise, the behavior is undefined. [ Note: If the value
i−jis not in the range of representable values of type
std::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.