1

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?
halfer
  • 19,824
  • 17
  • 99
  • 186
goodvibration
  • 5,980
  • 4
  • 28
  • 61
  • You can also use [Code Review](https://codereview.stackexchange.com/) – EsmaeelE Aug 30 '17 at 01:58
  • [CERT covers how to check for overflow](https://stackoverflow.com/a/19920014/1708801) and [clang and gcc have builtins that deal with overflow](https://stackoverflow.com/a/32317442/1708801) – Shafik Yaghmour Aug 30 '17 at 04:18

1 Answers1

1

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.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765