Question about -Wstrict-overflow=2

Alexander Motzkau a.motzkau@web.de
Sat Mar 6 10:37:03 GMT 2021


Hi everyone,

I have a question how to fix a -Wstrict-overflow=2 warning. Please consider
this (very) simplified example:

    #include <stdbool.h>
    #include <stddef.h>

    char* get_buf();
    bool do_round();

    bool fun()
    {
        char *expbuf = get_buf();
        char *argptr = expbuf;
        char *endbuf = expbuf + 120;

        while(true)
        {
            if (argptr >= endbuf)
                return false;

            if (!do_round())
                break;

            argptr++;
        }

        return true;
    }

gcc -O2 -Wstrict-overflow=2 gives a warning 'assuming pointer wraparound
does not occur when comparing P +- C1 with P +- C2 [-Wstrict-overflow]' for
the first if condition in GCC 9 as well as GCC 10. Although the wording of
the warning is questionable - the compiler may always assume I write
standard conforming code without telling me about it - the documentation
says this warning comes when a comparison is simplified to a constant.
A constant result would mean that the if block always or never happens
which would be quite undesirable.

Looking at the assembly output with Matt Godbolt's Compiler Explorer however
it seems that there's nothing wrong. GCC modified the loop to use an index
variable counting from 120 backwards. Clever, but clearly not a constant to
warn about.

So the question is what this warning is really about and how to get rid of
it?

If I change the condition to 'argptr - endbuf >= 0' the warning goes away,
but so does the optimization. The resulting code then has a worse
performance and worse readability.

Is there indeed something wrong with the code that I didn't see?
Or is there anything I can do to silence the warning apart from going to
-Wstrict-overflow=1?

Thanks,
Alex


More information about the Gcc-help mailing list