Definition
Unsigned modular arithmetic describes a counter that starts again at zero after its largest value. With value bits, the counter can display every whole number from 0 to . Try . The left bit counts for 2 and the right bit counts for 1. The four patterns 00, 01, 10 and 11 therefore mean 0, 1, 2 and 3. Add 1 to 11. The full sum is 100, or 4. A two-bit counter keeps the rightmost two bits, so it displays 00, or 0. Subtract 1 from that zero and it returns to 11, or 3.
C uses the same rule when an addition, subtraction or multiplication takes place in an unsigned type. The word modulo names the cycle length, which is 4 for the two-bit counter. In C, first check the type used for the calculation. For example, two unsigned bytes can both be promoted (converted) to int before the processor adds them. The width of the variables holding the inputs alone does not tell you the width of the calculation.
The idea
A car’s odometer with five digits shows 99,999 and then 00,000: it keeps only the last five decimal digits of the distance. An unsigned integer of bits keeps only the last binary digits of every result. Going up past the maximum restarts at 0, and going down past 0 restarts at the maximum. The analogy stops at direction: an odometer only counts up, while unsigned arithmetic also wraps on subtraction and multiplication.
Wrapping is useful. It is exactly what a binary adder does, so it costs nothing, and many algorithms §14.1 want it: hash functions and checksums §4.32 mix bits modulo , and a free-running timer that wraps still gives the right elapsed time as now - start (the Counter wraparound §6.21 entry shows why).
Wrapping is dangerous for quantities that can never be negative, such as lengths. A parser computes the payload length of a message as size - header. If an attacker sends a message shorter than its header, the true difference is negative, the unsigned result wraps to a number near the maximum, and a later copy of that many bytes runs far past the end of the buffer: a buffer overflow §4.4. Every step obeyed the C rules. The error is that the program used a defined result as if it were the true length.
How it works
Let be the number of value bits of an unsigned type, so that the type holds 0 to . For example, uint8_t holds 0 to 255, uint16_t holds 0 to 65,535, uint32_t holds 0 to 4,294,967,295, and a 64-bit size_t, the type C uses for object sizes, holds 0 to 18,446,744,073,709,551,615. Each addition, subtraction or multiplication works in two steps:
compute the true mathematical result ;
add or subtract as many times as needed to bring into the range 0 to .
C11, the 2011 edition of the ISO standard that defines the C language, states this rule in section 6.2.5, paragraph 9, and concludes that a computation on unsigned operands never overflows.
The rule has these consequences:
addition past the top wraps to the bottom: gives 0;
subtraction below zero wraps to the top: with gives ;
multiplication keeps the low bits of the true product;
negation gives for , and 0 for ;
division and remainder never leave the range, and division by zero is still undefined behavior §4.12.
In binary, reducing modulo means keeping the low bits and dropping the rest, which is what the processor’s adder does anyway.
The rule applies only where the operation actually runs in an unsigned type. The integer promotions §4.18 convert operands narrower than int, such as uint8_t, and uint16_t on a machine with a 32-bit int, to signed int before the operation, so their arithmetic does not wrap; the value wraps only when it is stored back into the narrow type (see the Integer promotion and conversion entry). Types such as unsigned int, uint64_t and size_t do the arithmetic themselves, and they wrap.
Because the wrap is defined, a program can detect it before or after the operation. Before: wraps exactly when , and wraps exactly when . After: r = a + b wrapped exactly when r < a. For a quantity that must not wrap, such as a length, the program tests before computing it.
Worked example
A parser on a machine with a 32-bit int holds size , the number of bytes received, and header , the length the header must have, both of type uint32_t. The true difference is . The type cannot hold , so C adds : . That value is , as the subtraction rule says. A copy of that many bytes from a 3-byte message runs about 4 GiB past the data. With a 64-bit size_t, the same subtraction gives . The repair tests first, if (size < header) reject();; here , so the message is rejected and the subtraction never runs.
Multiplication wraps the same way. A program reserves memory for count records of 4 bytes each with malloc(count * 4), where count is a uint32_t taken from a message, so the multiplication runs in 32 bits. Let count be , which is . The true product is , and the stored result is . The program reserves 4 bytes and then writes more than a billion records into them. A test before the multiplication accepts only counts up to , where means rounded down, and 1,073,741,825 fails it.
The type decides where the wrap happens. If size and header were uint8_t, both would be promoted to int, and size - header would be the int value , with no wrap; the test size - header < 0 would be true, whereas with uint32_t operands it is always false. Passing that as a size_t length, for example to memcpy, converts it to on a machine with a 64-bit size_t: the huge length appears again, this time from the conversion.
Stated precisely
Let be the number of value bits of an unsigned type , and let be the true mathematical result of , or for operands and whose arithmetic runs in . The stored result is the unique integer with for some integer , which counts the whole cycles of taken away (a negative means cycles were added). This is the nonnegative remainder of divided by , written . In the first worked example and , so and . In the second, , so and .
Two wrap tests follow. For addition, holds exactly when the sum wrapped: without a wrap , and with one , because . For subtraction, the result wrapped exactly when . Hence a difference of two lengths equals the true length exactly when .
Limits and common mistakes
Defined does not mean correct. A wrapped length, index or size is a valid number with a wrong meaning. The Common Weakness Enumeration (CWE), a public catalog of software weaknesses, lists the two directions as CWE-190, integer overflow or wraparound, and CWE-191, integer underflow (wrap or wraparound).
An unsigned type does not reject negative input. A length field declared unsigned receives an attacker’s as the maximum value, and a test such as len >= 0 is always true; many compilers can warn about such a test.
Counting down with an unsigned index never stops: in for (unsigned i = n - 1; i >= 0; i--) the condition is always true, and after i reaches 0 the decrement wraps it to the maximum.
Mixed signed and unsigned operands are often converted to unsigned, so -1 < 2u is false (see the Integer promotion and conversion entry).
A shift by at least the number of bits is still undefined behavior for unsigned operands (see the Shift semantics §4.20 entry).
Intentional wrapping needs its own argument. An elapsed time now - start is right only if the true elapsed time is less than ticks and the subtraction runs in the counter’s own width.
Questions answered
Can size minus header underflow into a huge positive length?
Yes, size minus header becomes a huge positive length whenever size is smaller than header and the subtraction runs in an unsigned type, such as uint32_t, unsigned int or size_t. An unsigned result cannot be negative, so C reduces the true negative difference modulo , where is the number of bits, which gives minus the shortfall: with 32 bits, gives , and with a 64-bit size_t it gives . This wrap is defined behavior, so no trap or error occurs, and a program that uses the result as a length reads or writes far beyond the message. Programmers call this an unsigned underflow.
The repair is to test size >= header before subtracting and to reject the message otherwise. Operands narrower than int, such as uint8_t, are first promoted to int and give a negative difference; the same huge length then appears when that difference is converted to an unsigned type such as size_t.
Related entries: Integer promotion and conversion (§4.18), Overflow-safe range check (§4.17), ALU32 versus ALU64 (§2.11), Signed integer overflow (§4.15), Counter wraparound (§6.21). Further reading: [78].