Integer Overflow to Undersized Allocation (CWE-190, CWE-680)
An integer overflow by itself only produces a wrong number. It becomes a memory-safety bug in one particular, very common chain: a size is computed from values in the input (width × height × bytes per pixel, count × element size, header + payload), the computation wraps around to a small number, malloc returns a small block, and the code that fills the block uses the original, large values. The allocation and the copy disagree, and the copy runs far past the end of the block. Image, font, video and archive decoders have produced a long series of advisories of exactly this shape. The arithmetic rules behind it (unsigned wraparound, signed overflow as undefined behaviour) are explained in Programming for Security's C Integer Types and Overflow; this lesson follows one bug from the multiplication to the heap overflow.
The bug in a toy program
The toy decodes an image header with a 32-bit width and height and allocates 4 bytes per pixel, computing the size in uint32_t. A normal 4×2 image needs 32 bytes. The second header is chosen so that the product just exceeds 2³²: 65,536 × 16,385 × 4 = 4,295,229,440 = 2³² + 262,144, so the 32-bit result wraps to 262,144. The fill loop then writes row after row using the real dimensions. Only the ASan build is run, because without ASan the loop would try to write 4 GB:
cat > img.c <<'SRC'
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* A toy image header from a file: width and height in pixels, 4 bytes per pixel. */
struct header { uint32_t width, height; };
static uint8_t *decode(const struct header *h) {
uint32_t bytes = h->width * h->height * 4; /* BUG: 32-bit multiply can wrap */
printf("%ux%u -> allocating %u bytes\n", h->width, h->height, bytes);
uint8_t *pixels = malloc(bytes);
if (!pixels) return NULL;
for (uint32_t y = 0; y < h->height; y++) /* fills width*height*4 bytes */
memset(pixels + (size_t)y * h->width * 4, 0x80, (size_t)h->width * 4);
return pixels;
}
int main(void) {
setvbuf(stdout, NULL, _IONBF, 0);
struct header ok = {4, 2}, evil = {0x10000, 0x4001}; /* 65536 x 16385 x 4 = 2^32 + 262144 */
free(decode(&ok));
free(decode(&evil));
return 0;
}
SRC
gcc -g -O0 -fsanitize=address,undefined img.c -o img && ./img 2>&1 | grep -E 'allocating|ERROR|WRITE|#1 |located|runtime'
echo "exit code: ${PIPESTATUS[0]}"
echo "== clang can flag the wrapping multiplication itself"
clang -g -O0 -fsanitize=address,unsigned-integer-overflow img.c -o img-c && ./img-c 2>&1 | grep -E 'runtime error' | head -24x2 -> allocating 32 bytes
65536x16385 -> allocating 262144 bytes
==15==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x746fa39ff800 at pc 0x746fa4f2997d bp 0x7fff8770c130 sp 0x7fff8770b8d8
WRITE of size 262144 at 0x746fa39ff800 thread T0
#1 0x60960a7f962f in decode /home/learner/img.c:15
0x746fa39ff800 is located 0 bytes after 262144-byte region [0x746fa39bf800,0x746fa39ff800)
allocated by thread T0 here:
#1 0x60960a7f9500 in decode /home/learner/img.c:12
exit code: 1
== clang can flag the wrapping multiplication itself
img.c:10:43: runtime error: unsigned integer overflow: 1073807360 * 4 cannot be represented in type 'uint32_t' (aka 'unsigned int')
The report, line by line
- The program's own line
65536x16385 -> allocating 262144 bytes: the size is 256 KiB for an image that needs 4 GiB. That line is where the bug is, even though nothing complains yet. heap-buffer-overflow … WRITE of size 262144: the second row'smemset(each row is 65,536 × 4 = 262,144 bytes). The first row filled the whole block exactly; the second starts right after it.#1 decode img.c:15and0 bytes after 262144-byte region … allocated by … img.c:12: the fill and the allocation.- GCC's UBSan said nothing, because unsigned wraparound is defined behaviour in C. Clang's
-fsanitize=unsigned-integer-overflowis a separate, opt-in check that reports it atimg.c:10:43:1073807360 * 4 cannot be represented in type 'uint32_t'. It is noisy in code that relies on wraparound on purpose (hashes, checksums), which is why it is not part ofundefined.
The two halves are worth naming separately: CWE-190 (integer overflow or wraparound) is the arithmetic, CWE-680 (Integer Overflow to Buffer Overflow) is the chain, and the resulting write is CWE-122.
Root cause
The size was computed in a type too narrow for the product of two input values, and the result was never checked. A second, design-level cause: the code had no idea what a reasonable image is. A 65,536 × 16,385 image is 4 GiB of pixels; a decoder for a web service should reject it long before the multiplication.
The fix
Three independent layers, each of which would have stopped this input:
- Validate the inputs against sane limits (here 16,384 pixels per side; real decoders choose limits of a similar order).
- Compute sizes in
size_twith checked arithmetic: C23'sckd_mulfrom<stdckdint.h>(GCC 14+, Clang 18+), or the older__builtin_mul_overflowin GCC and Clang. Both return true when the mathematical result doesn't fit. - Use the same expression for the allocation and the fill, so they can't disagree, or let
calloc(n, size)do the checked multiplication (it returns NULL on overflow).
#include <stdckdint.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct header { uint32_t width, height; };
#define MAX_SIDE 16384u
/* Returns the pixel buffer size, or 0 if the image must be rejected. */
static size_t image_bytes(const struct header *h) {
size_t px, bytes;
if (h->width == 0 || h->height == 0 || h->width > MAX_SIDE || h->height > MAX_SIDE)
return 0; /* layer 1: sane limits */
if (ckd_mul(&px, (size_t)h->width, (size_t)h->height) || ckd_mul(&bytes, px, (size_t)4))
return 0; /* layer 2: checked arithmetic */
return bytes;
}
int main(void) {
struct header tests[] = {{4, 2}, {0x10000, 0x4001}, {16384, 16384}, {0, 5}};
for (int i = 0; i < 4; i++) {
size_t n = image_bytes(&tests[i]);
if (!n) { printf("%5ux%-5u rejected\n", tests[i].width, tests[i].height); continue; }
printf("%5ux%-5u %zu bytes ok\n", tests[i].width, tests[i].height, n);
if (n <= 4096) { /* the demo allocates only small images */
uint8_t *px = calloc(n, 1); /* layer 3: one size for allocation and fill */
if (px) memset(px, 0x80, n);
free(px);
}
}
/* What 32-bit arithmetic would have said about the evil header: */
uint32_t wrapped;
int overflow = ckd_mul(&wrapped, (uint32_t)0x10000, (uint32_t)0x4001 * 4u);
printf("32-bit: overflow=%d, wrapped value=%u\n", overflow, wrapped);
return 0;
} 4x2 32 bytes ok
65536x16385 rejected
16384x16384 1073741824 bytes ok
0x5 rejected
32-bit: overflow=1, wrapped value=262144
The evil header is rejected by the side limit; in 64-bit arithmetic its product would not even overflow, which is why the sanity limit matters as much as the checked multiply. The largest allowed image, 16,384 × 16,384, needs exactly 1 GiB and is accepted; the zero-width one is rejected. The last line shows what ckd_mul would have reported for the original 32-bit expression: overflow, with the wrapped value 262,144 that the toy allocated.
How it is detected
- Review every size computation that involves input: multiplications, additions of a header size,
len + 1nearSIZE_MAX, and implicit narrowing intouint32_t/int(enable-Wconversionin new code). - Sanitizers:
-fsanitize=undefinedcatches signed overflow; Clang's-fsanitize=unsigned-integer-overflowand-fsanitize=implicit-conversioncatch wraparound and truncation; ASan catches the resulting overflow. - Fuzzing with dictionaries of boundary values (0, 1, 0x7fffffff, 0x80000000, 0xffffffff, 0x10000) for every integer field of a format.
- Static analysis: CodeQL and Coverity have taint-tracking queries for "user-controlled value used in allocation size".
Pitfalls
- Checking after the fact:
if (bytes / 4 / h->height != h->width)works for unsigned types but is easy to get wrong; prefer the builtins. - Moving to 64 bits isn't enough on its own: the product of two 32-bit values always fits in a 64-bit
size_t, but a third factor (even the* 4for bytes per pixel, with both sides near 2³²) can overflow again, and so can 64-bit lengths read from a file. - Signed sizes: computing in
intmakes the overflow undefined, and the compiler may delete your overflow check (C Integers).
Practice
1. Find a width and height (both at most 65,536) for which width * height * 4 wraps to exactly 0 in 32 bits.
Any pair with width × height = 2³⁰, for example 65,536 × 16,384: 2¹⁶ × 2¹⁴ × 2² = 2³² ≡ 0. malloc(0) may return a valid unique pointer to a zero-size block, and the first write overflows it.
2. Why does calloc(width * height, 4) not fix the bug?
The multiplication width * height is still done in 32 bits before calloc sees it. calloc checks only its own multiplication of its two arguments. Pass the values separately in size_t, or check first.
3. Which CWE numbers describe this chain?
CWE-190 (the wraparound), CWE-680 (integer overflow to buffer overflow) and CWE-122 (the heap overflow).
Test yourself
What did the toy allocate for the 65536 x 16385 image?
- 4 GiB
- 262,144 bytes, because the 32-bit product wrapped
- 0 bytes
- 1 GiB
Why didn't GCC's -fsanitize=undefined report the multiplication?
- It was disabled
- Unsigned wraparound is defined behaviour in C; only Clang's opt-in unsigned-integer-overflow check reports it
- The multiplication was signed
- GCC doesn't have UBSan
Which C23 facility performs checked multiplication?
- safe_mul in <stdlib.h>
- ckd_mul in <stdckdint.h>
- mul_s in <math.h>
- __builtin_mul only
Which CWE names the whole chain from wraparound to overflow?
- CWE-121
- CWE-680
- CWE-134
- CWE-401