Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler warning (or static analysis) for subtraction of unsigned integers?

Tags:

c++

g++

Consider the following program:

#include <iostream>

int main()
{
    unsigned int a = 3;
    unsigned int b = 7;

    std::cout << (a - b) << std::endl;  // underflow here!

    return 0;
}

In the line starting with std::cout an underflow is happening because a is lesser than b so a-b is less than 0, but since a and b are unsigend so is a-b.

Is there a compiler flag (for G++) that gives me a warning when I try to calculate the difference of two unsigend integers?

Now, one could argue that an overflow/underflow can happen in any calculation using any operator. But I think it is more dangerous to apply operator - to unsigend ints because with unsigned integers this error may happen with quite low (to me: "more common") numbers.

A (static analysis) tool that finds such things would also be great but I much prefer a compiler flag and warning.

like image 460
TobiMcNamobi Avatar asked Sep 08 '25 05:09

TobiMcNamobi


1 Answers

GCC does not (afaict) support it, but Clang's UBSanitizer has the following option [emphasis mine]:

-fsanitize=unsigned-integer-overflow: Unsigned integer overflow, where the result of an unsigned integer computation cannot be represented in its type. Unlike signed integer overflow, this is not undefined behavior, but it is often unintentional. This sanitizer does not check for lossy implicit conversions performed before such a computation

like image 150
dfrib Avatar answered Sep 09 '25 20:09

dfrib