C/C++ unsigned integer overflow

匿名 (未验证) 提交于 2019-12-03 09:06:55

问题:

i'm reading an article about integer security . here's the link: http://ptgmedia.pearsoncmg.com/images/0321335724/samplechapter/seacord_ch05.pdf

In page 166,there is said:

What does it mean? appreciate for reply.

回答1:

It means the value "wraps around".

UINT_MAX + 1 == 0 UINT_MAX + 2 == 1 UINT_MAX + 3 == 2 

.. and so on

As the link says, this is like the modulo operator: http://en.wikipedia.org/wiki/Modulo_operation



回答2:

It means that you can't alter the sign of a unsigned calculation, but it can still produce unexpected results. Say we have an 8-bit unsigned value:

 uint8_t a = 42; 

and we add 240 to that:

 a += 240; 

it will not fit, so you get 26.

Unsigned math is clearly defined in C and C++, where signed math is technically either undefined or implementation dependent or some other "things that you wouldn't expect may happen" wording (I don't know the exact wording, but the conclusion is that "you shouldn't rely on the behaviour of overflow in signed integer values")



回答3:

No overflow?

"Overflow" here means "producing a value that doesn't fit the operand". Because arithmetic modulo is applied, the value always fits the operand, therefore, no overflow.

In other words, before overflow can actually happen, C++ will already have truncated the value.

Modulo?

Taking a value modulo some other value means to apply a division, and taking the remainder.

For example:

0 % 3 = 0  (0 / 3 = 0, remainder 0) 1 % 3 = 1  (1 / 3 = 0, remainder 1)  2 % 3 = 2  (2 / 3 = 0, remainder 2) 3 % 3 = 0  (3 / 3 = 1, remainder 0) 4 % 3 = 1  (4 / 3 = 1, remainder 1) 5 % 3 = 2  (5 / 3 = 1, remainder 2) 6 % 3 = 0  (6 / 3 = 2, remainder 0) ... 

This modulo is applied to results of unsigned-only computations, with the divisor being the maximum value the type can hold. E.g., if the maximum is 2^16=32768, then 32760 + 9 = (32760 + 9) % (32768+1) = 0.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!