Lesson 6 of 14 · 20m
Integer Conversions: When -1 Beats Your Bounds Check
A signed `int len` slides past a `len > 255` check and lands in memcpy as SIZE_MAX — the conversion rules behind real allocator CVEs.
The parser reads a 32-bit length field, stores it in int len, rejects oversize records with if (len > MAX_PAYLOAD) return -1 — and the check waves -1 straight through, because -1 is not greater than 512. Three lines later memcpy(dst, src, len) converts that -1 to SIZE_MAX and tries to move an astronomically large buffer into a 256-byte stack slot. This is the integer-conversion bug: not the flamboyant signed-overflow UB of the previous lesson, but the quieter disaster of C's usual arithmetic conversions doing exactly what the standard says while you meant something else.
The wrong mental model: "int is a number." It isn't — it's a fixed-width slot with conversion rules, and the rules pick the winner in any mixed expression. When a signed int meets an unsigned size_t in a comparison, the signed operand converts to unsigned: if (-1 < 1U) is false, because -1 became UINT_MAX. That's what makes the bug selective: len < sizeof buf or len > sizeof buf against a negative int actually rejects it (it converts to SIZE_MAX), while len > 255 or len > maxlen against a signed bound lets it straight through — which is why code that "has bounds checks" still ships this.
The three conversion traps that account for most of the damage:
- Signed/unsigned comparison and the unchecked lower bound.
int len = -1versusif (len > 255):255is a signed literal, so the comparison stays signed,-1survives — thenmemcpy'ssize_tparameter wraps it toSIZE_MAX. The flip side:if (len > sizeof buf)does catch-1, becausesizeofissize_tand-1becomesSIZE_MAXin the comparison — the same conversion rule that bites you also occasionally saves you, which is why this bug confuses people. Rule: the packet field's declared width decides the type — read intouint32_t, bounds-check insize_t, and never let a signed type carry untrusted length data. - Truncation on assignment.
uint16_t len = full_size;silently keeps the low 16 bits;int fd_count = st.st_sizetruncatesoff_t. Warnings exist:-Wconversionflags these, and it finds real bugs — enable it in new code even though it screams on legacy trees. - Allocation arithmetic.
malloc(n * sizeof *items)with attacker-controllednwraps the product to something small — then your loop writesnitems into a 4-byte block. This is CVE-2002-0391's shape (the SunRPCxdr_arrayoverflow:size = n * elem_sizewrapped, undersized the array, remote root followed). The modern fix is boring and total:calloc(n, size)makes the allocator check the product, and glibc has done so since the fix;__builtin_mul_overflow(n, sizeof *items, &total)checks it yourself; C23 finally standardizedckd_mulin<stdckdint.h>.
The pattern that kills the whole class:
size_t total;
if (__builtin_mul_overflow(count, sizeof *items, &total))
return -1;
items = calloc(count, sizeof *items); /* belt and suspenders: calloc
checks the same product and
zero-fills */
if (!items)
return -1;One more that hides in loops: for (size_t i = n - 1; i >= 0; i--) never terminates, because size_t can't go below zero — i >= 0 is always true and the wrap to SIZE_MAX makes the condition immortal. Write for (size_t i = n; i-- > 0;) or use a signed index when the logic needs one.
Try this
Write the int len parser bug in ten lines: int len = -1; if (len > 255) return -1; memcpy(buf, src, len);. Compile gcc -O2 -Wall — clean, no warning. Run it under -fsanitize=address and watch ASan abort on the memcpy — the "safe" check passed. Now change len to size_t and note the assignment itself is where the negative input should have been impossible — the type change is the fix.
Field notes
sizeof,strlen, andread's third argument aresize_t. Keep your counters insize_tand the mixed-comparison bug class mostly evaporates; cast only at the boundary, deliberately.charhas implementation-defined signedness — signed on x86, unsigned on ARM by default.isdigit(c)on rawcharis UB whencis negative; cast tounsigned charfirst. Real CVEs have shipped on the ARM port alone.- The field width is the contract: read a
u32field intouint32_t, check it against remaining bytes, and only then truncate to what you need.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
Implementing UART on the ATmega328P
USART on the AtMega328P Needed Documentation * Arduino Nano PCB design * Atmega328P datasheet Materials used * Arduino Nano * Arduino Uno R3 * Relevant cable * Computer Software Used * make (for easy of compiling and building) * avr-gcc (our compiler for avr ISA) *…
Hello World, Embedded Edition: Blink an LED
Embedded C: Hello WorldNeeded DocumentationArduino Nano PCB designAtmega328P datasheetMaterials usedArduino NanoArduino Uno R3Relevant cableComputerSoftware Usedmake (for easy of compiling and building)avr-gcc (our compiler for avr ISA)binutils-avravr-libcavrdude (used to flash board)The…
Build Your Own Stack-Based Bytecode Virtual Machine in C
Ever wonder how Python's CPython, the JVM, or the Lua VM actually execute code under the hood? In this article, we build a stack-based bytecode virtual machine from scratch in C.
CPPFront Project is Aiming to Modernize the C++ Language
The highly vaunted C++ language would become simpler and safer under a proposal dubbed Cppfront, an experimental C++ front end being floated by prominent C++ developer Herb Sutter. Intended as a major C++ evolution, Cppfront is an experimental “syntax 1 to syntax 2” compiler designed to explore…