Integer overflow and underflow happen when numbers go beyond their allowed limits. This can cause wrong results or bugs in programs.
0
0
Integer overflow and underflow in Blockchain / Solidity
Introduction
When working with cryptocurrency balances that must not exceed or go below certain values.
When counting tokens or assets in a smart contract to avoid errors.
When performing math operations that could produce very large or very small numbers.
When validating user inputs that affect numbers stored on the blockchain.
When designing secure contracts to prevent attackers from exploiting number limits.
Syntax
Blockchain / Solidity
// Example in Solidity uint8 smallNumber = 255; smallNumber += 1; // causes overflow int8 negativeNumber = -128; negativeNumber -= 1; // causes underflow
Unsigned integers (like uint8) can only hold positive numbers and zero.
Signed integers (like int8) can hold positive and negative numbers.
Examples
Adding 1 to the max value 255 causes overflow and wraps around to 0.
Blockchain / Solidity
uint8 x = 255; x += 1; // x becomes 0 due to overflow
Subtracting 1 from the min value -128 causes underflow and wraps around to 127.
Blockchain / Solidity
int8 y = -128; y -= 1; // y becomes 127 due to underflow
Adding numbers safely when total stays within allowed range.
Blockchain / Solidity
uint256 balance = 1000; balance += 500; // safe addition if within limits
Sample Program
This Solidity contract shows integer overflow on a uint8 variable. The addOne function adds 1 to 255, causing overflow to 0 inside an unchecked block.
Blockchain / Solidity
pragma solidity ^0.8.0; contract OverflowExample { uint8 public smallNumber = 255; function addOne() public { unchecked { smallNumber += 1; // overflow happens here } } function getNumber() public view returns (uint8) { return smallNumber; } }
OutputSuccess
Important Notes
Modern Solidity versions (0.8.0+) check for overflow by default and throw errors.
Using unchecked disables these checks and allows overflow/underflow.
Always be careful with unchecked math to avoid security risks.
Summary
Integer overflow happens when a number goes above its max limit and wraps around.
Integer underflow happens when a number goes below its min limit and wraps around.
In blockchain, these can cause bugs or security problems if not handled properly.