Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ unsigned integer overflow

Tags:

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:

A computation involving unsigned operands can never overflow,because a result that cannot be represented by the resulting unsigned integer type is reduced modulo to the number that is one greater than the largest value that can be represented by the resulting type.

What does it mean? appreciate for reply.

like image 294
Detective King Avatar asked Apr 17 '13 09:04

Detective King


People also ask

Can unsigned integers overflow?

A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.

Is unsigned overflow defined C?

Many unsigned integer overflows in C and C++ are well- defined, but non-portable. For example 0U-1 is well-defined and evaluates to UINT_MAX, but the actual value of that constant is implementation defined: it can be relied upon, but only within the context of a particular compiler and platform.

What is unsigned overflow?

If you are doing two's complement (signed) arithmetic, overflow flag on means the answer is wrong - you added two positive numbers and got a negative, or you added two negative numbers and got a positive. If you are doing unsigned arithmetic, the overflow flag means nothing and should be ignored.

Does C have integer overflow?

In C, unsigned integer overflow is defined to wrap around, while signed integer overflow causes undefined behavior.


2 Answers

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

like image 85
Pubby Avatar answered Oct 14 '22 18:10

Pubby


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.

like image 38
Sebastian Mach Avatar answered Oct 14 '22 19:10

Sebastian Mach