User: Password:
Subscribe / Log in / New account

GCC and pointer overflows

GCC and pointer overflows

Posted Apr 16, 2008 21:22 UTC (Wed) by zooko (guest, #2589)
Parent article: GCC and pointer overflows

I painstakingly wrote a macro over a course of years that does this:

Macro which evaluates true if the expression (x+y) will result in arithmetic 
overflow.  It also evaluates true if one of the operands is negative and the 
other is of a type that is too large to fit into a long long (because the 
result of the addition is not guaranteed in the C89 standard).

Treat it as though it were defined something like this:

bool ADD_WOULD_OVERFLOW({anyinttype} x, {anyinttype} y);

I'm not 100% certain that I got all the edge cases right, but at least it passes my own test

One of the key insights to write this macro is this:  while "x + y < x" is not guaranteed to
be valid (if one of them is signed), "MAX_INT - x < y" is.

#define ADD_WOULD_OVERFLOW_Styp(x, y, typ) ((((x) > 0) && ((y) > 0) && ((Z_MAX_typ(typ) - (x))
< (y))) || (((x) < 0) && ((y) < 0) && ((Z_MIN_typ(typ) - (x)) > (y))))

(Log in to post comments)

GCC and pointer overflows

Posted Apr 16, 2008 22:33 UTC (Wed) by gravious (guest, #7662) [Link]

How about?

CLEAR_CARRY_FLAG // arch dep macro
if (CARRY_FLAG_IS_SET) // arch dep macro

Surely an easy to find out if something WOULD_OVERFLOW is to perform the operation and check

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