C Integer Types and Overflow
Many memory-safety bugs start as arithmetic bugs. A length read from a packet is added to a header size and wraps around to a small number; the small number passes the bounds check; the copy then uses the original, huge length. A count multiplied by an element size overflows, malloc returns a tiny buffer, and the loop that fills it writes far past its end. A negative int is compared with an unsigned size and becomes four billion. These bugs (CWE-190 integer overflow, CWE-191 underflow, CWE-195 signed-to-unsigned conversion) are behind many advisories for image decoders, network stacks and kernels. The rules of C's integer types are covered in C; this lesson is about where they bite.
Definitions
- Width:
uint8_t0–255,uint16_t0–65535,int32_t−2,147,483,648 to 2,147,483,647,uint32_t0–4,294,967,295;size_tis unsigned and 64 bits on 64-bit Linux. - Unsigned wraparound: unsigned arithmetic is modulo 2ⁿ by definition:
UINT32_MAX + 1 == 0. Defined, but often wrong. - Signed overflow: undefined behaviour. The compiler may assume it never happens and remove checks written as
if (x + 1 < x). - Usual arithmetic conversions: when a signed and an unsigned value of the same width meet, the signed one is converted to unsigned:
-1 < 1uis false. - Truncation: assigning a wider value to a narrower type keeps the low bits:
(uint8_t)300 == 44. - Checked arithmetic: GCC and Clang provide
__builtin_add_overflow(a, b, &r)and__builtin_mul_overflow, which return true when the mathematical result does not fit; C23 standardises them asckd_addandckd_mulin<stdckdint.h>.
Four ways the numbers lie
#include <stdint.h>
#include <stdio.h>
#include <string.h>
int main(void) {
/* 1. A bounds check defeated by unsigned wraparound */
uint32_t hdr = 16, len = 0xFFFFFFF8u; /* len chosen by the sender */
uint32_t total = hdr + len; /* wraps to 8 */
printf("1. hdr+len = %u, check total <= 64: %s\n", total, total <= 64 ? "PASSES" : "fails");
/* 2. Allocation size overflow: count * size */
uint32_t count = 0x40000001u, size = 4;
uint32_t bytes32 = count * size; /* wraps to 4 */
size_t r;
int ovf = __builtin_mul_overflow((size_t)count, (size_t)size, &r);
printf("2. 32-bit count*size = %u bytes; in size_t = %zu (overflow: %d)\n", bytes32, r, ovf);
uint32_t r32;
printf(" checked 32-bit multiply overflows: %s\n", __builtin_mul_overflow(count, size, &r32) ? "yes" : "no");
/* 3. Signed length meets unsigned size */
char buf[16];
int n = -1; /* e.g. an error code used as a length */
printf("3. n < sizeof buf: %s; as size_t n = %zu\n", (n < (int)sizeof buf) ? "true" : "false", (size_t)n);
printf(" without the cast: %s\n", ((size_t)n < sizeof buf) ? "true" : "false (n became huge)");
/* 4. Truncation into a narrow field */
uint32_t payload = 70000;
uint16_t wire_len = (uint16_t)payload;
printf("4. payload %u stored in 16 bits = %u\n", payload, wire_len);
(void)buf;
return 0;
}1. hdr+len = 8, check total <= 64: PASSES
2. 32-bit count*size = 4 bytes; in size_t = 4294967300 (overflow: 0)
checked 32-bit multiply overflows: yes
3. n < sizeof buf: true; as size_t n = 18446744073709551615
without the cast: false (n became huge)
4. payload 70000 stored in 16 bits = 4464
Each line is a real bug shape. In (1) the check sees 8 and passes, while a copy of len bytes would read 4 GB. In (2) a 32-bit size computation asks malloc for 4 bytes for a billion elements; the checked multiply catches it. In (3) -1 passes a signed check, and if it is then passed to memcpy (whose length is size_t) it becomes 18,446,744,073,709,551,615. In (4) a length that does not fit a 16-bit protocol field is silently cut, so the receiver reads only part of the message, and the rest is parsed as the next message (a smuggling bug).
Undefined behaviour, caught by UBSan
Signed overflow is worse than wraparound because it is undefined: the optimiser may delete a check that depends on it. The session compiles a "safe" check written the wrong way, then runs it with UndefinedBehaviorSanitizer, which reports the overflow with its file, line and values. It runs in your sandbox.
cat > ovf.c <<'SRC'
#include <limits.h>
#include <stdio.h>
int add_len(int a, int b) {
if (a + b < a) /* intended overflow check: relies on UB */
return -1;
return a + b;
}
int add_len_checked(int a, int b) {
int r;
if (__builtin_add_overflow(a, b, &r))
return -1;
return r;
}
int main(void) {
printf("checked: %d\n", add_len_checked(INT_MAX - 2, 10));
printf("naive: %d\n", add_len(INT_MAX - 2, 10));
return 0;
}
SRC
gcc -g -O0 -fsanitize=undefined ovf.c -o ovf && ./ovf 2>&1
echo "== -O2, no sanitizer: is the naive check still there?"
gcc -O2 ovf.c -o ovf2 && ./ovf2
objdump -d --no-show-raw-insn ovf2 | awk '/<add_len>:/,/ret/' | sed 's/^ *[0-9a-f]*:\t//'ovf.c:5:11: runtime error: signed integer overflow: 2147483645 + 10 cannot be represented in type 'int'
checked: -1
naive: -1
== -O2, no sanitizer: is the naive check still there?
checked: -1
naive: -2147483641
0000000000001190 <add_len>:
endbr64
test %esi,%esi
js 119c <add_len+0xc>
lea (%rsi,%rdi,1),%eax
ret
UBSan names the exact operation: a signed addition at ovf.c:5 whose result can't be represented in int. At -O0 the naive check happened to work, because the machine's addition wrapped. At -O2 the compiler reasons that a + b < a can only be true if signed overflow happened, which "cannot happen", so it reduces the test to b < 0. With b = 10 the check is skipped, and the naive function returns a large negative number instead of -1. The checked version is correct at every optimisation level.
How integer bugs are detected
- Sanitizers in tests and fuzzing:
-fsanitize=undefined(signed overflow, shifts, invalid conversions) and Clang's-fsanitize=integer(also unsigned wraparound and implicit truncation, which are not UB but often bugs). - Compiler warnings:
-Wall -Wextra -Wconversion -Wsign-compare -Wsign-conversionflag implicit narrowing and mixed comparisons. Noisy in old code, valuable in new code. - Code review of every length or count from input: where it is added, multiplied, cast, compared, and used as an allocation size or index. Static analysers (CodeQL's "user-controlled arithmetic" queries, Coverity) trace these paths.
How they are fixed
- Check before computing:
if (len > MAX - hdr) reject;instead ofif (hdr + len > MAX), or use__builtin_add_overflow/ckd_add. - Use
calloc(count, size), which checks the multiplication, orreallocarray(); nevermalloc(count * size)with untrustedcount. - Keep lengths unsigned and wide (
size_t), convert input once at the edge with a range check, and never use error codes as lengths. - Validate protocol fields against their own width before encoding: a 16-bit length field means payloads above 65,535 are rejected or split, not truncated.
- Compile with
-fwrapvor-ftrapvonly as a stopgap: they change the language's rules, they don't fix the logic.
Pitfalls
- Integer promotion:
uint8_t a = 200, b = 100; a + bis300(promoted toint), but storing it back inagives44. abs(INT_MIN)is undefined and in practice returnsINT_MIN, still negative.- Loops with unsigned counters:
for (size_t i = n - 1; i >= 0; i--)never ends, becausei >= 0is always true. - Shifts:
1 << 31on a 32-bitintis undefined; use1u << 31.
Practice
1. A parser does if (offset + length > file_size) return ERR; memcpy(dst, base + offset, length); with all three uint32_t. Construct values that pass the check and copy out of bounds, then fix it.
offset = 0x100, length = 0xFFFFFF80, file_size = 0x1000: the sum wraps to 0x80, which is not greater than file_size. Fix: if (offset > file_size || length > file_size - offset) return ERR;, which can't wrap.
2. What does (uint8_t)(250 + 10) evaluate to, and why might a firewall rule parser care?
260 mod 256 = 4. A parser that stores a port-range end or a counter in 8 bits could turn "allow up to 260" into "allow up to 4", or a TTL check into the wrong value. Validate the range before narrowing.
3. Why did the -O2 build print a negative number for the naive function?
The compiler is allowed to assume signed overflow never happens, so a + b < a was simplified to b < 0, which is false for b = 10. The function returned the wrapped sum, INT_MAX - 2 + 10 modulo 2³², which is negative.
Test yourself
With uint32_t, what is 16u + 0xFFFFFFF8u?
- 4294967304
- 8
- 0
- Undefined
Why is if (a + b < a) a broken overflow check for signed int?
- It is too slow
- Signed overflow is undefined behaviour, so the compiler may simplify or remove the check
- It only works for unsigned values
- It always returns true
Which allocation is safe against count * size overflow?
malloc(count * size)calloc(count, size)malloc(count) * sizealloca(count * size)
What is (size_t)-1 on 64-bit Linux?
- -1
- 0
- 18446744073709551615
- 4294967295