Suppose we have:
char* p;
int x;
As recently discussed in another question, arithmetic including comparison operations on invalid pointers can generate unexpected behavior in gcc linux x86-64 C++. This new question is specifically about the expression (p+x)-x
: can it generate unexpected behavior (i.e., result not beingp
) in any existing GCC version running on x86-64 linux?
Note that this question is just about pointer arithmetic; there is absolutely no intention to access the location designated by *(p+x)
, which obviously would be unpredictable in general.
The practical interest here is non-zero-based arrays. Note that (p+x)
and the subtraction by x
happen in different places in the code in these applications.
If recent GCC versions on x86-64 can be shown to never generate unexpected behavior for (p+x)-x
then these versions can be certified for non-zero-based arrays, and future versions generating unexpected behavior could be modified or configured to support this certification.
UPDATE
For the practical case described above, we could also assume p
itself is a valid pointer and p != NULL
.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…