https://gcc.gnu.org/bugzilla/show_bug.cgi?id=110933

            Bug ID: 110933
           Summary: Add warning flags to check against integer overflow
           Product: gcc
           Version: unknown
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: mail+gcc at nh2 dot me
  Target Milestone: ---

GCC currently lacks good compile-time warnings that help find common integer
overflow bugs.

For example, the code

    #include <stdint.h>

    void f(uint64_t n)
    {
        for (uint32_t i = 0; i < n; ++i) {
        }
    }

will loop forever if `n` happens to be around 5 billion.

This is a mistake many programmers make (I've had to fix multiple instances of
this in common Free Software programs, and similar instances in the Linux
kernel).
The bug is not easy to spot because this standard incrementing-loop construct
looks "very terminating", and it gets much harder when typedefs, macros, or C++
type templates are involved.

(I would like to file this feature request both for C and C++, but Bugzilla
doesn't allow that, so I'm picking C++.)

Existing warnings such as `-Wsign-compare` are of the right spirit, but do not
help with e.g. simple unsigned integers.

In 
https://stackoverflow.com/questions/76840686/how-can-i-get-a-warning-when-comparing-unsigned-integers-of-different-size-in-c/

I asked for current ways to find such issues. The best current approaches are a
non-trivial clang-query invocation, and closed-source tools such as PVS Studio.

It would be better if GCC itself had better warnings to help with this.

In the above case, we have a binary operator between a wider and a narrower
integer type, and implicit (invisible) upcasting (widening) happens.

Having a flag to warn about such implictly-converting binary ops would go a
long way, but maybe there's a more general approach to this.

The implementation of such flag should probably consider some common benign
special cases, such as comparing with an integer literal that gets upcast (`x >
0` vs `0ul` -- safe since this constant exists in both domains).

It is clear that such warning would likely not be on by default, but it could
help tremendously for modernising software projects that e.g. weren't written
with a 64-bit mindset.

Reply via email to