GCC and pointer overflows
Posted Apr 16, 2008 22:49 UTC (Wed) by aegl
Parent article: GCC and pointer overflows
I'm having some dificulty parsing the rationale by which this optimization is allowed.
"in a correct program, pointer addition will not yield a pointer value outside of the same object"
Is gcc deciding that "buffer + len < buffer" makes this an "incorrect" program, so it can generate any random code (in this case no code at all) because the program is "incorrect" and so deserves to die?
Could gcc get more radical and apply the same logic to the first clause of this test? The declaration of "buffer" is in scope and "buffer_end" is statically initialized and never changed (OK ... it would have to be declared "static" for gcc to be really sure about this, so lets pretend that it was). So a test for "buffer + len >= buffer_end" appears to be just as "incorrect" if you believe that pointer addition will not yield a pointer "outside of the same object".
I'm sure the intent of the "same object" rule is to stop programmers from making assumptions about the proximity of different objects. E.g.
int a, b, *p = a;
p += 5;
/* should not assume that p now points to "b" */
It seems a bit of a stretch to get from this to outlawing a test like "buffer + len < buffer".
to post comments)