Integer overflow and underflow happen when arithmetic produces a result outside the range a fixed-size integer can hold, so it wraps around: subtracting 1 from 0 in a uint becomes the maximum value (underflow), and adding past the maximum returns to 0 (overflow). In smart contracts this can turn a small operation into a huge, attacker-controlled balance. Solidity 0.8.0+ reverts on overflow by default, but older code, unchecked blocks, and unsafe casts remain vulnerable. The fix is a modern compiler or SafeMath.
What it is
Smart contract integers are fixed-size and unsigned by default (for example uint256, range 0 to 2^256-1). If a calculation goes below 0 or above the maximum, it does not error in older Solidity, it wraps:
- Underflow:
0 - 1becomes the maximumuintvalue (a colossal number). - Overflow:
max + 1becomes0.
When that wrapped value is a token balance or amount, the consequences are severe, a user can mint themselves an enormous balance from a tiny subtraction.
How it works and example
A pre-0.8 transfer that underflows on balance check:
function transfer(address to, uint amount) public {
require(balances[msg.sender] - amount >= 0); // always true for uint
balances[msg.sender] -= amount; // underflows if amount > balance
balances[to] += amount;
}
Since a uint is never negative, the require is meaningless, and subtracting more than the balance underflows to a massive number, giving the attacker an enormous balance to spend. Documented for defensive context.
How to defend
- Use Solidity 0.8.0 or later, where checked arithmetic reverts on overflow/underflow by default.
- On older code, use a SafeMath library for all arithmetic.
- Audit every `unchecked { }` block, those opt out of the protection.
- Validate casts between integer sizes (
uint256touint128) that can silently truncate. - Test boundary values (0, max) and fuzz arithmetic-heavy logic.
References
- [1]SWC Registry: Smart Contract Weakness Classification(SWC Registry)
- [2]Solidity docs: Security considerations(Solidity)
- [3]MITRE CWE-190: Integer Overflow or Wraparound(MITRE CWE)