Our website uses cookies to enhance your browsing experience.
Accept
to the top
>
>
>
V3217. Possible overflow as a result...
menu mobile close menu
Additional information
toggle menu Contents

V3217. Possible overflow as a result of an arithmetic operation.

Feb 05 2025

The analyzer has detected an arithmetic operation that may result in an overflow.

The example:

private const int _halfMaximumValue = int.MaxValue / 2;

public void Calculate(int summand)
{
    int sum;

    if (summand > _halfMaximumValue + 1)
    {
        sum = _halfMaximumValue + summand;
    }

    ....
}

In the Calculate method, the sum of the passed parameter and the constant is calculated. The constant is equal to half of the maximum System.Int32 value. The parameter value is checked before the addition operation to avoid the arithmetic overflow.

However, the condition contains an error. In this case, there is a check whether summand is greater than _halfMaximumValue + 1. If the condition is true, the arithmetic overflow will occur during the addition operation.

For proper check execution, replace the > operator with <:

private const int _halfMaximumValue = int.MaxValue / 2;

public void Calculate(int summand)
{
    int sum;

    if (summand < _halfMaximumValue + 1)
    {
        sum = _halfMaximumValue + summand;
    }

    ....
}

Overflow can occur when using unverified external data as an operand:

private const int _halfMaximumValue = int.MaxValue / 2;

public void Calculate()
{
  var numberStr = Request.QueryString["number"];

  if (Int32.TryParse(numberStr, out int number))
  {
    int sum = _halfMaximumValue + number;
    ....
  }
}

The numberStr value, obtained from the external source, is converted to int and assigned to the number variable. Then, number is added to _halfMaximumValue. This may lead to an overflow if number is greater than half of the maximum int value.

To prevent this overflow issue, limit number before performing the addition:

private const int _halfMaximumValue = int.MaxValue / 2;

public void Calculate()
{
  var numberStr = Request.QueryString["number"];

  if (   Int32.TryParse(numberStr, out int number)
      && number < 1000) // <=
  {
    int sum = _halfMaximumValue + number;
    ....
  }
}

This diagnostic is classified as: