Arithmetic Overflow and underflow

Envision an older car’s odometer (non digital) that only supports 999,999. Once it crosses 999,999 it will revert back to 000,000. In cars this is not a big deal but in computer programming this can have serious consequences. In programming this is an example of integer overflow.


An overflow in Solidity occurs when a number is incremented beyond its maximum value. As an example suppose we declare an uint8 variable, which can take up to 8 bits. This means that it can have decimal numbers between 0 and 2^8-1 = 255. Consider the following code.

uint8 a=255;

some function

Incrementing this the variable “a” by 1 would result in an overflow situation because its maximum value is 255. Remember Solidity can handle up to 256-bit numbers. So Uint overflow is when there is a number greater than the uint max which results in the number looping back to 0.

Under flow works in the opposite direction. Remember how uint8 can take values only between 0 and 255. Consider the following code.

uint8 a=0;

some function

The code above caused an underflow which results in “a'” having the maximum possible value which is 255.

Prevent overflow and under flow

To prevent underflow and overflow problems in your solidity smart contract code you can use the SafeMath library by openZepplin. The safe math library will help you check for overflows in case of addition, underflow in case of subtraction as well as when performing multiplications and divisions.

SafeMath Libraries can be found here on Github – SafeMath by openZepplin .

OpenZeppelin is a company that builds developer tools and performs security audits on smart contracts. They are well known in the block chain industry and their contacts are available on Github to download and use. They offer a lot of contracts for use and a lot of well known deployed contracts use their code.

Next Review – Reentrancy attack in a Solidity smart contract


Leave a Reply