LWN.net Logo

GCC and pointer overflows

GCC and pointer overflows

Posted Apr 17, 2008 16:01 UTC (Thu) by wahern (subscriber, #37304)
In reply to: GCC and pointer overflows by kleptog
Parent article: GCC and pointer overflows

if (~sizeof buf < len) {
    die();
}

This only works with unsigned values, and there are probably some caveats with width and
promotion rules (portable, nonetheless).

Also, assuming your environment uses linear addressing, and there's no other funny stuff going
on with pointer bits (like the effectively 16 free bits on AMD64--using 48-bit addressing).

if (~(uintptr_t)buf < len)  {
    die();
}

I believe this should work on Windows and all Unix systems (guaranteed by additional SUSv3
constraints), but I'm not positive.


(Log in to post comments)

GCC and pointer overflows

Posted Apr 17, 2008 22:03 UTC (Thu) by jzbiciak (✭ supporter ✭, #5246) [Link]

Of course, it fails for dynamically allocated and grown buffers since sizeof() can't tell you the length.

Also, you failed to account for element size. The following should work, though, for arrays of static size:

    if (len > (sizeof(buf) / sizeof(buf[0]))
       die_in_a_fire();

I don't understand why you have the bitwise negation operator in there. Also, len is a length, not a pointer type, so pointer format doesn't matter.

GCC and pointer overflows

Posted Apr 19, 2008 5:51 UTC (Sat) by wahern (subscriber, #37304) [Link]

The question was how to check if arithmetic overflowed/wrapped, not whether an index or length
is valid.


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