goodvibration
goodvibration

Reputation: 6206

Verifying a test for multiplication-overflow

I have implemented the following function for detecting whether or not a multiplication overflows:

bool IsSafeMul(uint32_t x, uint32_t y) {
    uint32_t z = x * y;
    return (z >= x && z >= y);
}

I have verified it empirically, but would like to ensure that:

  1. Is it 100% guaranteed to work correctly (i.e., no false-positives and no false-negatives)?
  2. Is it 100% guaranteed to work correctly for any other unsigned type?

Upvotes: 1

Views: 116

Answers (1)

AnT stands with Russia
AnT stands with Russia

Reputation: 320747

No, it is not guaranteed to work correctly. For example,

0x000FFFFF * 0x000FFFFF = 0xFFFFE00001 

It produces 0xFFE00001 after truncation to 32 bits, which passes your test. But multiplication overflows.

To test for overflow on multiplication you can simply check z / x == y provided x is not zero.

Upvotes: 1

Related Questions