Skip to content
Back to Curriculum
SECURITY

Overflow & Underflow

Fixed-size integers have limits. `uint8` goes from 0 to 255. If you calculate `255 + 1`, it historically wrapped around to `0`. Solidity 0.8+ now automatically reverts on overflow, but understanding it is crucial for legacy code and `unchecked` blocks.

Syntax Structure

Example.sol
Loading...

Key Components

  • Boilerplate structure required by the Solc compiler.
  • Placement of state variables versus functions.

Practical Implementation

Demonstrating the wrap-around behavior in an unchecked block.

Practical.sol
Loading...

Core Concepts

Wrap Around

Like a car odometer, after 999999 comes 000000.

SafeMath

Legacy library (OpenZeppelin) used to prevent this before 0.8.0.

Panic(0x11)

The error code Solidity throws on overflow.

Mental Model

The Odometer

If you have a 3-digit combination lock (000-999) and you are at 999, adding 1 rolls it back to 000. It doesn't break; it just loops. In banking software, 'looping' your balance from $0 to $Infinity (underflow) is catastrophic.

Under the Hood

The EVM does NOT check for overflow by default. `ADD` simply adds. Solidity adds extra bytecode (`JUMPI` checks) around every math op. `unchecked` removes these checks.

ADDLTJUMPIREVERT

Gas Analysis

Safe math costs gas.

  • • Use `unchecked` only when you are mathematically 100% sure overflow is impossible (e.g. iterating a bounded array).
  • • Saves ~100 gas per operation.

Security Risks

The source of infinite money glitches.

  • ! BEC Token Attack: Attacker caused an underflow to give themselves billions of tokens.
  • ! Logic Errors: Assuming `a - b` is always positive.

Common Use Cases

Historical Audits (SafeMath era).
Optimizing gas with `unchecked`.
Understanding weird token balances.

Interactive Visualization

See exactly how the EVM handles this code in memory, storage, and the stack.

Interactive Simulation
0 / 0
Loading...
Type Solidity code (v0.8.26) and click Run. Compiler loads on first use (~2MB).

Click Run to execute the simulation

Then use the step controls to navigate