What is integer overflow and underflow and how it can be possible? I saw its example that coders avoid this bug by require(balanceOf(_to) +_value >= balanceOf(_to)) where _value is an unsigned integer so it will always be positive and will add to the balance, so this is an understood thing so why is this condition needed?

1 Answer 1


Solidity does not have any built-in protection from over/underflow. This means that if you hit the min or the max of a value (0 or 2^256-1 = 115792089237316195423570985008687907853269984665640564039457584007913129639935) then the value will "wrap" around and keep counting.

Put the following code in Remix to test it out.

pragma solidity ^0.5.16;

contract FlowTest {

    uint256 public a = 0;
    uint256 public b = 2**256-1; 

    function flow () external {
        a -= 1;
        b += 1;

If you deploy this contract, you will see that a and b are 0 and 2^256-1, respectively. If you run flow(), you will see that they switch and a = 2^256 - 1 and b = 0. This is because a underflowed and b _overflowed`.

If you run flow() once more, you will see that a = 2^256-2 and b = 1.

OpenZeppelin's SafeMath.sol is a widely used library that helps with this.

  • 1
    Thanks for the answer and correcting the question, can you please elaborate what does wrap refer to here?
    – uzair kath
    May 10, 2020 at 0:30
  • You can read more here javapapers.com/core-java/java-overflow-and-underflow. Imagine if you are trying to count to 11 on your fingers, you will not be able to because you have 10 fingers. Solidity is not smart enough to realize you only have 10 fingers, so when it adds 1 to your 10th "finger", it will start over at 1. May 10, 2020 at 0:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.