Don't shoot your foot: Integer promotion edition

In my previous post I've talked about signed integer overflows, how do they happen, and why are they so dangerous.

However, the problem is, that sometimes these overflows are come from an unexpected source. To get the idea, please take a look at the following code:

unsigned short a = 0xFFFF;
unsigned short b = 0xFFFF;
auto c = a * b;        

If you can't see Undefined Behaviour here, it doesn't mean there isn't. In fact, this code has the same problem of signed integer overflow, but now it's happening because of an amazingly annoying mechanism: integer promotion.

The need for integer promotions originates from the fact that operations on numbers (addition, subtraction, multiplication, division) are not defined for all the numeric types. For example, unsigned short is one of these types. In order to make mathematical operations possible, numbers are promoted.

In general, it looks like this:

  1. Those types, which are smaller than int, are promoted to signed int, even if both of the operands are unsigned. That's exactly what happens with the example above: two unsigned shorts are promoted to signed ints, and the result of their multiplication doesn't fit into a signed int - that's how the overflow occurs.
  2. If operands are of different types and of different width, the smaller type is promoted to the wider type.
  3. If operands are of different types of the same width, then signed types are promoted to unsigned.

More details can be found on cppreference.com.

So, my recommendations are:

  • Use static analysis tools to catch operations with numbers of mixed signs.
  • Be careful with numbers that are smaller than int.

要查看或添加评论,请登录

Mark Kirichenko的更多文章

  • Don't shoot your foot: auto edition

    Don't shoot your foot: auto edition

    I've recently seen a Linkedin post where people argued about the keyword "auto" in C++ and the potential issues which…

    3 条评论
  • Don't shoot your foot: narrowing and extending

    Don't shoot your foot: narrowing and extending

    In my previous posts, I've mentioned the problem of integer promotions, and how they can cause Undefined Behaviour. In…

    1 条评论
  • Don't shoot your foot: signed overflow edition

    Don't shoot your foot: signed overflow edition

    Recently myself and my colleague Johan Moraal discussed a critical vulnerability in FreeRTOS kernel and the patch which…

    2 条评论

社区洞察

其他会员也浏览了