Understanding Integer Overflow
What you'll learn: How computers behave when a variable reaches its maximum capacity and "wraps around" like an odometer.
The Odometer Effect
Imagine the mileage tracker in an old car that only has five digits. When you reach 99,999 miles and drive just one more mile, the display doesn't show 100,000—it physically cannot. Instead, it flips back to 00,000.
In C, variables have similar physical limits based on their type. Because memory is finite, an unsigned integer has a maximum value it can hold. If you try to add 1 to that maximum, the computer doesn't crash; it simply "overflows" and wraps back around to the smallest possible value (zero).
Seeing it in Code
In the example below, we use a short integer. On most systems, an unsigned short maxes out at 65,535. Watch what happens when we push it past the edge:
#include <stdio.h>
int main() {
// A 16-bit unsigned short maxes out at 65,535
unsigned short score = 65535;
printf("Current score: %u\n", score);
// Adding 1 causes an overflow
score = score + 1;
printf("Score after adding 1: %u\n", score);
return 0;
}
If you run this, the second line won't say 65,536. It will print 0.
Signed vs. Unsigned Overflow
The behavior changes slightly depending on whether your data type allows negative numbers:
- Unsigned types: These are predictable. They always wrap back to
0. Think of it like a circular clock; after 12 comes 1. - Signed types: These are more dangerous. Because signed integers use one bit to track the "sign" (positive or negative), overflowing a signed integer often results in the number suddenly becoming a large negative value. In professional C programming, signed overflow is considered "undefined behavior," meaning the computer might do something unexpected or even crash.
Understanding overflow is vital for security. If a programmer doesn't account for these limits, a "large" deposit in a bank app could theoretically wrap around and leave a user with a balance of zero—or worse, a negative debt could wrap around to become a massive fortune.
Key takeaway
Integer overflow occurs when a value exceeds its type's capacity, causing it to wrap around to its minimum value.