Notifications
Clear all
Topic starter 15/08/2025 9:11 pm
An integer overflow is a subtle but serious bug that occurs when a calculation produces a number outside the range that can be represented by a given integer type.
🔢 What Is an Integer Overflow?
Every integer type (like int
, short
, long
) has a fixed size in memory—usually 8, 16, 32, or 64 bits. This limits the range of values it can store.
💥 Overflow Happens When:
- You add, subtract, or multiply numbers and the result exceeds the maximum value the type can hold.
- The value wraps around to the minimum (or vice versa), often silently.
📉 Example: Overflow in C++
#include <iostream>
#include <limits>
int main() {
int max = std::numeric_limits<int>::max(); // 2,147,483,647
int result = max + 1; // Overflow!
std::cout << "Result: " << result << std::endl;
}
🧨 Output:
Result: -2147483648
The value wraps around to the minimum of a signed 32-bit integer. No error is thrown!
🧠 Why Is This Dangerous?
- Security vulnerabilities: Integer overflows can lead to buffer overflows, privilege escalation, or logic bypasses.
- Incorrect calculations: Financial, scientific, or game logic can break.
- Silent failures: Many languages don’t warn you when overflow occurs.
🛡️ How to Prevent It
✅ Use Safe Types and Checks
- Use larger types (
long long
,uint64_t
) if needed. - Check for overflow before performing operations.
if (a > INT_MAX - b) {
// Handle overflow
}
✅ Use Compiler Flags
- GCC/Clang:
-ftrapv
to trap overflows - Enable warnings:
-Wall -Wextra
✅ Use Safe Libraries
Languages like Rust and Swift offer built-in overflow protection:
let x: u8 = 255;
let y = x + 1; // Panic in debug mode
🧪 Real-World Exploit Example
The Heartbleed bug in OpenSSL involved a form of unchecked length calculation—an integer overflow that led to reading sensitive memory.