[Python-Dev] Memory size overflows

Gerald S. Williams gsw@agere.com
Wed, 16 Oct 2002 11:12:05 -0400


Guido van Rossum wrote:
> I.e. a macro callable as
>   SAFE_MULTIPLY(destination, src1, src2, on_overflow);
> meaning roughly
>   destination = src1 * src2;
>   if (<overflow detected>)
>      on_overflow;

> There are also additions...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.

Why not use the same trick for multiplication? For src1,src2 > 0,
dest should always be >= MAX(src1,src2). SAFE_MULTIPLY could be
implemented something like this:

#define HALF_BITS (sizeof(size_t) * 4U)
#define LO_MASK ((((size_t)1) << (HALF_BITS))-1)
#define HI_MASK (~(LO_MASK))
#define MAX(a,b) (((a) >= (b)) ? (a) : (b))

#define SAFE_MULTIPLY(dest,src1,src2,on_error)  \
    {                                           \
        size_t _x = src1;                       \
        size_t _y = src2;                       \
        size_t _dest = _x * _y;                 \
                                                \
        if (_x && _y && ((_x|_y) & HI_MASK))    \
        {                                       \
            if (_dest < MAX(_x,_y))             \
            {                                   \
                on_error;                       \
            }                                   \
        }                                       \
                                                \
        dest = _dest;                           \
    }

-Jerry Williams