GCC and pointer overflows
GCC and pointer overflows
Posted Apr 16, 2008 19:50 UTC (Wed) by iabervon (subscriber, #722)Parent article: GCC and pointer overflows
Note that the wrap-around check isn't necessarily sufficient if sizeof(*buffer) > 1, as in:
int buffer[BUFLEN];
int *buffer_end = buffer + BUFLEN;
/* ... */
unsigned int len;
if (buffer + len >= buffer_end || buffer + len < buffer)
loud_screaming_panic("len is out of range\n");
At a bit more than 1/(sizeof int) of MAX_INT, the pointer sum will probably go back through the buffer. For ideal security on this sort of stuff, GCC would generate code where a pointer addition that overflows compares greater than any valid pointer value when compared in the same expression. It should be more efficient than the second check anyway, since it's only checking processor flags on calculations it's doing anyway in a correctly-predicted not-taken branch.