
The Overflow Bug That Ate Pac-Man: Why 1+1 Isn't Always 2 in Code
How integer overflow silently corrupts programs — from Pac-Man's infamous level 256 glitch to the Ariane 5 disaster — and how to defend your code against it.
In 1982, arcade players discovered something deeply wrong on Pac-Man's 256th board. Instead of the familiar maze, the left half of the screen dissolved into a chaotic jumble of symbols, the fruit counter glitched, and the level read "0." The game wasn't broken by a design flaw or a corrupted cartridge — it was felled by a single byte that ran out of room. That byte was an 8-bit integer, and it had just committed the most classic bug in software: integer overflow. Four decades later, the same bug has destroyed a $370 million rocket, grounded a fleet of airliners, and is still silently corrupting production systems. This deep dive explains exactly how integer overflow works under the hood, why it's so hard to catch, and how to defend your code against it.
- 1. The Pac-Man Level 256 Glitch
- 2. How Integers Are Stored in Binary
- 3. What Overflow Actually Is
- 4. Why Overflow Is So Dangerous
- 5. When Overflow Kills: Real Disasters
- 6. Overflow Semantics by Language
- 7. Detecting and Preventing Overflow
- 8. Best Practices for Overflow-Proof Code
- Frequently Asked Questions
1. The Pac-Man Level 256 Glitch
Pac-Man's level counter is stored in a single 8-bit unsigned integer at a fixed RAM address. An 8-bit value can hold exactly 256 distinct values: 0 through 255. That's plenty for the first 255 levels — but the moment the player clears level 255 and the game increments the counter, the byte has nowhere to go. It wraps around to 0.
The game uses that same byte as an index into a table of fruit symbols — the cherry, strawberry, orange, apple, and melon icons that appear above the maze at the start of each board. When the level counter wraps to 0, the game looks up fruit symbol index 0, which happens to be the "turning" symbol — a special animation frame used when Pac-Man turns a corner. The game dutifully stamps that symbol across the left half of the screen, producing the famous garbled "kill screen." The right half renders a normal maze, but the left half is a wall of glitchy fruit sprites, the level display reads "0," and the board is effectively unplayable.
Level byte (0-255) --> indexes fruit symbol table
|
+-- 255 = last valid level
+-- 256 wraps to 0 --> draws fruit[0] = "turning" symbol
+-- left half of screen gets filled with that symbol
The Pac-Man bug is a perfect case study because it's so small and so easy to understand: one byte, one wrap, one broken screen. But the same mechanism — a value that exceeds its representable range and silently wraps — is responsible for some of the most expensive software failures in history.
2. How Integers Are Stored in Binary
Every integer in a computer is a fixed-width sequence of bits. An 8-bit value has 8 bits, each contributing a power of two. For an unsigned integer, the value is the sum of the set bits:
128 64 32 16 8 4 2 1
1 0 1 1 0 1 0 0 = 180
The maximum unsigned value for n bits is 2^n − 1. For 8 bits, that's 255. For 16 bits, 65,535. For 32 bits, 4,294,967,295. For 64 bits, 18,446,744,073,709,551,615.
Signed integers use two's complement, which represents negative numbers by inverting the bits and adding one. The most significant bit becomes the sign bit, and the range shifts to −2^(n−1) through 2^(n−1) − 1. For a signed 8-bit integer, that's −128 to 127.
| Width | Unsigned range | Signed range (two's complement) |
|---|---|---|
| 8-bit | 0 to 255 | −128 to 127 |
| 16-bit | 0 to 65,535 | −32,768 to 32,767 |
| 32-bit | 0 to 4,294,967,295 | −2,147,483,648 to 2,147,483,647 |
| 64-bit | 0 to 18,446,744,073,709,551,615 | −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
Here's a tiny Python helper that shows the binary representation of any integer in a given width:
def to_binary(n: int, bits: int = 8) -> str:
"""Return the two's complement binary representation of n in 'bits' bits."""
mask = (1 << bits) - 1
return format(n & mask, f'0{bits}b')
print(to_binary(255)) # 11111111
print(to_binary(0)) # 00000000
print(to_binary(-1)) # 11111111 (two's complement)
print(to_binary(-128)) # 10000000
The key takeaway: every integer type has a hard ceiling. When arithmetic pushes a value past that ceiling, something has to give.
3. What Overflow Actually Is
Integer overflow happens when the result of an arithmetic operation cannot be represented in the destination type's range. The behavior that follows depends entirely on the language and the signedness of the type.
Unsigned integers in C, C++, and Go are defined to wrap modulo 2^n. Adding 1 to 255 in a uint8_t always produces 0. This is guaranteed by the standard, so it's not a "bug" in the language sense — it's a defined behavior that often surprises programmers.
#include <stdio.h>
#include <stdint.h>
int main(void) {
uint8_t level = 255;
level = level + 1; // wraps to 0, defined behavior
printf("level after 255 + 1: %u\n", level); // prints 0
return 0;
}
Signed integers in C and C++ are different: signed overflow is undefined behavior (UB). The compiler is allowed to assume it never happens, and it may optimize code on that basis. In practice, on most hardware, signed overflow wraps too — but you cannot rely on it, and aggressive optimizations can produce genuinely surprising results.
Java defines signed overflow as wrapping, always. Integer.MAX_VALUE + 1 evaluates to Integer.MIN_VALUE — no exception, no UB, just a silent wrong answer.
public class Overflow {
public static void main(String[] args) {
int x = Integer.MAX_VALUE;
System.out.println(x + 1); // -2147483648
}
}
Python sidesteps the entire problem: integers are arbitrary precision. 2**1000 is computed exactly, with as many bits as needed. No overflow, ever.
print(2**1000) # 10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
Rust takes a stance: in debug builds, overflow panics (aborts with a message). In release builds, it wraps by default — but you can opt into checked, wrapping, saturating, or overflowing arithmetic explicitly.
fn main() {
let x: u8 = 255;
// Debug build: panics with "attempt to add with overflow"
// Release build: wraps to 0
let y = x + 1;
println!("{}", y);
}
The point is: the same expression 255 + 1 produces 0 in C, 0 in Java, a giant number in Python, and a crash in Rust debug builds. The behavior is a property of the language, not the hardware — and it's a trap for anyone who assumes all languages behave alike.
4. Why Overflow Is So Dangerous
The most insidious thing about integer overflow is that it usually fails silently. The program keeps running, the value is simply wrong, and that wrong value propagates into array indices, buffer sizes, loop counters, security checks, and financial calculations. By the time anyone notices, the damage is done.
In C and C++, it's worse. Because signed overflow is undefined behavior, compilers are free to assume it never happens — and they will optimize on that assumption. Consider this function:
// Compiler assumes x + 1 > x is ALWAYS true for signed int,
// because signed overflow is undefined behavior.
int check(int x) {
return x + 1 > x;
}
At -O2, GCC and Clang both compile check to simply return 1;. The comparison is eliminated entirely. If you were relying on check(INT_MAX) to return 0 (because INT_MAX + 1 wraps to INT_MIN in two's complement), you'd be wrong — the compiler has decided that code path is unreachable and removed it.
This is why overflow bugs in C/C++ are not just "wrong values." They are optimization hazards. A single overflowing operation can cause the compiler to delete code you thought was protecting you. Security researchers have exploited this in real vulnerabilities: the compiler removes a bounds check because it "proves" the index can't overflow, and an attacker gets an out-of-bounds write.
The lesson: overflow is a correctness bug, a security bug, and a compiler-optimization bug all at once.
5. When Overflow Kills: Real Disasters
Ariane 5 (1996)
The most famous overflow disaster is the maiden flight of the Ariane 5 rocket on June 4, 1996. About 40 seconds after launch, the rocket veered off course and self-destructed. The cost: $370 million.
The root cause was a conversion overflow in the inertial reference system. The guidance software converted a 64-bit floating-point value (horizontal velocity) into a 16-bit signed integer. The velocity was far higher than the 16-bit range could hold — about 32,767 — so the conversion overflowed. The software didn't handle the overflow; it triggered an exception that shut down the guidance system, and the backup system failed the same way. The rocket was destroyed.
The irony: the same software had worked flawlessly on the Ariane 4, which had lower velocities. The overflow was a silent design assumption that happened to hold on one rocket and not another.
Boeing 787 (2015)
In 2015, the FAA issued an airworthiness directive for the Boeing 787 after a software bug caused both of the aircraft's generator control units to shut down. The cause: a counter in the generator control unit software overflowed after 248 days of continuous power. The counter held the number of power-on cycles, and when it exceeded its maximum, the software entered a fault state that shut down the generators. If it happened on both units simultaneously, the aircraft would lose all electrical power mid-flight.
The fix was a software update that resets the counter before it can overflow. The lesson: even a counter that increments once per power cycle — something that seems impossible to overflow — can be a hazard if the system runs continuously for months.
The Year 2038 Problem
The Unix time_t type stores seconds since January 1, 1970. On 32-bit systems, it's a signed 32-bit integer, which overflows on January 19, 2038, at 03:14:07 UTC. When that happens, the value wraps to a negative number, and every system that uses it will report dates in 1901. Most modern systems have moved to 64-bit time_t, but countless embedded devices, legacy systems, and file formats still use 32-bit. The clock is ticking.
6. Overflow Semantics by Language
Here's a comparison of how different languages handle integer overflow. Understanding your language's default is step one to preventing the bug.
| Language | Signed overflow | Unsigned overflow | Checked arithmetic available? |
|---|---|---|---|
| C / C++ | Undefined behavior | Wraps modulo 2^n | __builtin_add_overflow (GCC/Clang), _Generic |
| Java | Wraps (two's complement) | N/A (no unsigned) | Math.addExact, Math.multiplyExact |
| C# | Wraps in unchecked, throws in checked | Wraps | checked block, System.Math |
| Python | Arbitrary precision | N/A | Not needed |
| Rust | Panics in debug, wraps in release | Panics in debug, wraps in release | checked_add, saturating_add, wrapping_add, overflowing_add |
| Go | Wraps | Wraps | None built-in; use math/bits |
| JavaScript | All numbers are doubles; bitwise ops truncate to 32-bit | N/A | Number.isSafeInteger |
The JavaScript row deserves a note: JS numbers are IEEE 754 doubles, so 1e20 + 1 === 1e20 because of precision loss, not overflow. But bitwise operators (&, |, <<, >>) convert operands to 32-bit integers, so 1 << 31 produces -2147483648 — a classic source of overflow bugs in JS.
7. Detecting and Preventing Overflow
Compiler flags and sanitizers
For C and C++, the first line of defense is undefined behavior sanitizer (UBSan). It instruments arithmetic operations to detect overflow at runtime and reports it before it corrupts anything.
gcc -fsanitize=undefined -fno-sanitize-recover=undefined -g -O1 -o app app.c
With -fno-sanitize-recover=undefined, the program aborts on the first detected UB, turning a silent bug into a loud crash you can debug. Clang supports the same flags. You can also use -ftrapv to make signed overflow trap (abort) and -fwrapv to force wrapping behavior if you rely on it.
For the whole project, run these in CI on every build. UBSan has low overhead (single-digit percentages) and catches most overflow bugs immediately.
Built-in checked arithmetic in C
GCC and Clang provide __builtin_add_overflow, __builtin_sub_overflow, and __builtin_mul_overflow, which return a boolean indicating whether the operation overflowed and write the result to a pointer:
#include <stdio.h>
#include <stdint.h>
#include <limits.h>
int main(void) {
int a = INT_MAX, b = 1, result;
if (__builtin_add_overflow(a, b, &result)) {
fprintf(stderr, "overflow detected: %d + %d\n", a, b);
return 1;
}
printf("sum: %d\n", result);
return 0;
}
These are the fastest, most portable way to do checked arithmetic in C. C23 adds stdckdint.h with ckd_add, ckd_sub, and ckd_mul as standard alternatives.
Rust's explicit overflow modes
Rust forces you to choose how overflow should behave:
fn main() {
let a: u8 = 255;
let b: u8 = 1;
match a.checked_add(b) {
Some(v) => println!("sum: {}", v),
None => eprintln!("overflow detected!"),
}
println!("saturating: {}", a.saturating_add(b)); // 255
println!("wrapping: {}", a.wrapping_add(b)); // 0
let (v, overflowed) = a.overflowing_add(b);
println!("overflowing: {} (overflowed: {})", v, overflowed);
}
checked_add returns None on overflow, saturating_add clamps to the maximum, wrapping_add wraps, and overflowing_add returns the result plus a flag. There's no ambiguity — you decide.
Java's exact math
Java provides Math.addExact, Math.subtractExact, Math.multiplyExact, and Math.incrementExact, which throw ArithmeticException on overflow:
public class CheckedMath {
public static void main(String[] args) {
try {
int x = Math.addExact(Integer.MAX_VALUE, 1);
System.out.println(x);
} catch (ArithmeticException e) {
System.err.println("overflow detected!");
}
}
}
Python: just use it
Python's arbitrary-precision integers make overflow a non-issue for most use cases. The cost is performance and memory, but for correctness-critical code, it's often the pragmatic choice. If you're doing heavy numeric work in Python, libraries like NumPy have fixed-width types that can overflow — so the same caution applies there.
Static analysis
Beyond runtime sanitizers, static analyzers can catch overflow at compile time. Clang's -Wtautological-constant-out-of-range-compare, GCC's -Woverflow, and tools like Coverity, PVS-Studio, and CodeQL all flag suspicious arithmetic. They're not a substitute for runtime checks, but they catch the easy cases early.
8. Best Practices for Overflow-Proof Code
-
Know your types. Before writing arithmetic, ask: what's the maximum value this variable can hold? If you're counting something, use a type that can't overflow — a 64-bit counter for anything that might run for months, or an arbitrary-precision type if you're not sure.
-
Use checked arithmetic in security-critical code. Any time the value feeds into an array index, a buffer size, an allocation, or a security check, use
checked_add/Math.addExact/__builtin_add_overflow. Never let a wrapped value reach a bounds check. -
Enable sanitizers in CI. Run UBSan (and ASan) on every build. The overhead is small, and it converts silent corruption into a test failure with a stack trace.
-
Never mix signed and unsigned in C/C++. Implicit conversions between signed and unsigned types are a massive source of overflow and comparison bugs. Compile with
-Wsign-conversionand treat warnings as errors. -
Avoid relying on wrapping behavior. Even if your language defines wrapping, it's usually a bug. If you genuinely need modular arithmetic, use an explicit
wrapping_add(Rust) or document the intent clearly. -
Use a language that makes overflow explicit. Rust's debug-build panics and Python's arbitrary precision are both features, not limitations. If you're choosing a language for a new project, consider how it handles this.
-
Fuzz your inputs. Property-based testing tools like QuickCheck, Hypothesis, and cargo-fuzz can generate boundary values automatically. Add tests for
MAX_VALUE,MIN_VALUE, and values one past the boundary. -
Document your assumptions. If a function expects its input to be in a certain range, state it in a comment or an assertion. The Ariane 5 disaster was fundamentally an undocumented assumption about velocity range.
Frequently Asked Questions
Q: Is unsigned integer overflow always a bug?
A: No. Unsigned overflow is defined behavior — it wraps modulo 2^n by design. It's only a bug if the wrapping produces an incorrect result for your program. For example, a checksum or hash function might intentionally rely on wrapping. But in most application code, a wrapped value is an error. The key is to be intentional: if you rely on wrapping, document it; if you don't, check for it.
Q: Why does signed integer overflow cause undefined behavior in C/C++ instead of just wrapping?
A: Historically, different hardware handled signed overflow differently — some trapped, some wrapped, some produced garbage. The C standard chose to leave it undefined so compilers could target any hardware efficiently. This gives compilers freedom to optimize, but it means you cannot rely on any particular behavior. If you want defined wrapping, cast to an unsigned type first, or use -fwrapv.
Q: How do I test for overflow bugs in my codebase?
A: The most effective approach is a combination: (1) compile with UBSan (-fsanitize=undefined) and run your test suite; (2) enable static analysis warnings like -Woverflow and -Wsign-conversion; (3) add property-based tests that generate boundary values (0, 1, MAX, MAX−1, MIN, MIN+1); and (4) fuzz any function that takes untrusted input. These four layers catch the vast majority of overflow bugs before they reach production.
For more deep dives on systems programming and language internals, see Tamiz's Insights.