[Python-Dev] Memory size overflows

Tim Peters tim.one@comcast.net
Wed, 16 Oct 2002 01:44:02 -0400


[Guido]
> ...
> There are also additions, usually of small constants, which generally
> operate on the size_t.  These are easier to test: if you add a small
> positive constant to a size_t, and the result is smaller than the
> original size_t, an overflow occurred.

More generally, if x and y are both size_t, and sizeof(size_t) >=
sizeof(unsigned int), x+y overflowed if and only if

    x+y < x

Checking

    x+y < y

is equivalent -- you can compare the sum to either input; doesn't matter.

> Similar for plain ints.

Signed ints are harder.  If the signs differ, overflow is impossible.  If
the signs are the same, overflow occurred if and only if the sign of the
result differs from the common input sign.

    sum = x+y
    overflow iff ((sum ^ x) & (sum ^ y)) < 0

> So I'm not sure we need much help with these.

Well, they're all obscure as hell.