DEV Community

Mahima Thacker
Mahima Thacker

Posted on

OverFlow and UnderFlow causes in Solidity

In Solidity, arithmetic overflow and underflow were common issues before version 0.8.0.

Here's a quick overview of UnderFlow and OverFlow:

What is Overflow and Underflow?

Overflow:

When you add 1 to the maximum value of a uint8 (255), it exceeds the range (0-255). Solidity doesn't store values beyond 255, so it wraps back to 0.

Have a look at a function called overflow from the attached image, and the result you will get is 0

Image description

Underflow:

When you subtract 1 from the minimum value of a uint8 (0), it goes below the range (negative values aren't allowed). Solidity wraps back to 255.

so this is what we get when we call the function underflow from an image

Image description

But in Solidity 0.8.0 or Above it reverts with an error (overflow/underflow checks are enabled).

Why Does This Matter?

Overflow and underflow could lead to severe vulnerabilities in smart contracts, especially in financial calculations.

How to Prevent This? 🕵‍♀️

  • Use Solidity 0.8.0 or above, where overflow/underflow checks are built-in.
  • For older versions, use libraries like OpenZeppelin’s SafeMath.
  • Test edge cases to ensure safety in arithmetic operations.

Top comments (0)