GCC and pointer overflows
Posted Apr 17, 2008 0:01 UTC (Thu) by
im14u2c (subscriber, #5246)
Parent article:
GCC and pointer overflows
pointer addition will not yield a pointer value outside of the same object
Just some pedantry, but I believe you're allowed to point to the first element after the end of an array, as long as you don't dereference that element. Pointer comparisons with such a pointer are supposed to work, too.
That said, the problem is very similar to time comparison, where you have a running time counter that could wrap around, but all measured intervals still fit within the total size of the time-counter type. There, the safe way to do things is to keep the time as an unsigned value, and subtract off the base.
You can't really do that here, because ptrdiff_t really ought to be a signed type. In this case, if you keep "len" in a signed variable, negative lengths are always an error and so you can check for them directly before adding to a pointer base. Positive lengths can always be compared against the buffer size. In either case, you're comparing indices against each other, not pointers.
Comparing against a generated pointer is a premature optimization, and begs for the compiler to slap you. This is especially true when the pointer is to a type for which sizeof(type) > 1. For a large structure, the address arithmetic could wrap around several times, even for relatively small indices. Imagine a structure for which sizeof(type) == 65536. Any length > 32767 causes problems on a 32-bit system. Granted, arrays of such large structures tend to be very rare.
(
Log in to post comments)