Search code examples
c++g++gcc-warning

GCC strict-overflow


We recently turned on -Wstrict-overflow=5 for a large codebase, and are trying to understand the ~500 warnings when optimization is turned on. Some seem legitimate, but then there are things like this:

std::vector<std::string> files;

// ...

void Add (const std::string file)
{
  if (std::find(files.begin(), files.end(), file) == files.end())
  {
    files.push_back(file);
  }
}

which produces the warning:

example.cc: In member function ‘void Add(std::string)’:
example.cc:465:8: error: assuming signed overflow does not occur when changing X +- C1 cmp C2 to X cmp C2 -+ C1 [-Werror=strict-overflow]
void Add (const std::string file)
    ^

I assume the comparison is in std::find(), and exposed by inlining the Add() function.

How am I supposed to fix this?

Yes, I've read the other Stack Overflow questions, but nothing very helpful:

23020208 std::find on a std::set. Answer: GCC bug, turn off the warning

18521501 Refactor conditionals

22798709 Edge case in signed integers


Solution

  • How am I supposed to fix this?

    Since they are false positives caused by something you have no control over (i.e., GCC), you'll need to adjust to it:

    1. Take them one by one (this is why you enabled them in the first place, to detect where overflow may happen, right?)
    2. for those places where the compiler is right, apply corrections
    3. for the places where this is a false positive, use a #pragma to locally disable the warning - the presence of that #pragma will mean: "Due dilligence paid, I checked and there isn't any way something may overflow here".

    (The serenity prayer may help.)