>
>
>
V1081. Argument of abs() function is mi…


V1081. Argument of abs() function is minimal negative value. Such absolute value can't be represented in two's complement. This leads to undefined behavior.

The smallest negative value of a signed integer type has no corresponding positive value. When 'abs', 'labs', and 'llabs' functions evaluate this integer's absolute value, a signed integer overflow happens. This causes undefined behavior.

Example:

#include <iostream>
#include <cmath>
#include <limits.h>

int main()
{
  int min = INT_MIN;

  // error: abs(-2147483648) = -2147483648
  std::cout << "abs(" << min << ") = "
            << abs(min);                // <=

  return 0;
}

The minimum value of the 32-bit signed int type is 'INT_MIN' which equals -2147483648. At the same time, this type's maximum value - 'INT_MAX' - is 2147483647. This number is one less than the absolute value of 'INT_MIN'. In this case, calculating the absolute value yielded a negative number equal to the argument's original value. This can lead to an error in the corner case when the code is not intended to process negative numbers, because this code does not expect numbers to be negative after an absolute value is calculated.

For the remaining numbers, the function calculates absolute values as expected:

int main()
{
  int notQuiteMin = INT_MIN + 1;

  // ok: abs(-2147483647) = 2147483647
  std::cout << "abs(" << notQuiteMin << ") = "
            << abs(notQuiteMin);

  return 0;
}

Before calculating the absolute value, you could add a special argument check. It would help you avoid the corner case we discussed earlier:

void safe_abs_call(int value)
{
  if (value == INT_MIN)
    return;

  std::cout << "abs(" << value << ") = " << abs(value);
}

You can suppress the diagnostic if the de facto range of values supplied to 'abs', 'labs' and 'llabs' cannot reach the minimum value.

This diagnostic is classified as: