Re: Detecting overflows while computing off_t



Richard Tobin wrote:

In article <slrneoncai.2rv.cheney@xxxxxxxxxxxxxxxx>,
Andre Majorel <cheney@xxxxxxxxxxxxxxx> wrote:

How do you compute an off_t with overflow detection ?

A sometimes useful fact, if you know that overflow behaves as addition
mod 2^N (where N is the size in bits), is that a+b overflows if and
only if a+b < a (for positive a and b). So you can do the addition
and check for overflow by comparing the result to either of the
operands. For unsigned integer types in C, overflow must behave this
way. For signed types, it is still true for most implementations.

Overflow for signed types is undefined behavior
and allowing it to happen is not the way to write a correct program.

If A and B have opposites signs
or at least one of them is equal to zero, then (A+B) won't overflow.
If A and B are positive, and A_MAX - b > a, then (A+B) won't overflow.
If A and B are negative, and a > A_MIN - b, then (A+B) won't overflow.

--
pete
.



Relevant Pages