User: Password:
Subscribe / Log in / New account

GCC and pointer overflows

GCC and pointer overflows

Posted Apr 16, 2008 20:58 UTC (Wed) by JoeBuck (guest, #2330)
In reply to: GCC and pointer overflows by iabervon
Parent article: GCC and pointer overflows

The compiler then would have to insert such a check into every array reference in a loop, and your code would run about 3x slower. After all, they could wrap around the end, right?

But in a properly structured program, such checks are not needed, as pointers are not random, but rather refer to objects that have definite sizes and that do not wrap around the end of memory. If you think that you need such a check, there's something wrong with your program structure, some check that was omitted elsewhere. What matters is the size of the buffer, and you can go beyond its end without wrapping around the end of the address space.

(Log in to post comments)

GCC and pointer overflows

Posted Apr 17, 2008 14:06 UTC (Thu) by iabervon (subscriber, #722) [Link]

How so? I was only suggesting that the expression "pointer1 + offset >= pointer2" be treated
differently (that is, the magic does away if you store the LHS in a variable and use the
variable). (And, of course, the change would only apply to cases where the LHS overflows the
address space, which is clearly undefined, so having odd things matter isn't a problem.)

If you do something with "pointer + offset" other than comparing it with something else, I
wouldn't have anything change (what would it do, anyway, without a test and branch in the
code?); and in the case where you're doing the comparison, processors generally have a status
bit that gets updated in the multiply/shift and add and is pretty much free to have an
unlikely jump based on. Except on architectures where the instruction decode significantly
limits the pipeline, it should be at most one cycle to test so long as you do each test right
after the ALU operation.

C, in general, doesn't make good use of the fact that processors make it trivial to test for
overflow, but that doesn't mean that C compilers can't do extra-clever things with this
ability in cases where there's undefined behavior associated with it.

Copyright © 2017, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds