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

            Bug ID: 89161
           Summary: Bogus -Wformat-overflow warning with value range known
           Product: gcc
           Version: 7.4.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: lavr at ncbi dot nlm.nih.gov
  Target Milestone: ---

The following code

$ cat bogus1.c
#include <stdio.h>

static char* print(const unsigned short a[2])
{
    static char buf[3];
    if (a[0]  &&  a[0] < a[1])
        sprintf(buf, ".%1u", (10 * a[0]) / a[1]);
    else
        *buf = '\0';
    return buf;
}

unsigned short array[2];

int main()
{
    printf("%s\n", print(array));
    return 0;
}

produces a lot of noise when compiled optimized (no warning without):

$ gcc -Wall -O6 -c bogus1.c
bogus1.c: In function ‘main’:
bogus1.c:7:24: warning: ‘%1u’ directive writing between 1 and 10 bytes into a
region of size 2 [-Wformat-overflow=]
         sprintf(buf, ".%1u", (10 * a[0]) / a[1]);
                        ^~~
bogus1.c:7:22: note: directive argument in the range [0, 2147483647]
         sprintf(buf, ".%1u", (10 * a[0]) / a[1]);
                      ^~~~~~
bogus1.c:7:9: note: ‘sprintf’ output between 3 and 12 bytes into a destination
of size 3
         sprintf(buf, ".%1u", (10 * a[0]) / a[1]);
         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

even though the compiler could have figured out that because of the "if", the
value range of the integer division expression is actually [0..9], which
perfectly fits into the buffer provided for the sprintf() statement.

$ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-pc-cygwin/7.4.0/lto-wrapper.exe
Target: x86_64-pc-cygwin
Configured with:
/cygdrive/i/szsz/tmpp/gcc/gcc-7.4.0-1.x86_64/src/gcc-7.4.0/configure
--srcdir=/cygdrive/i/szsz/tmpp/gcc/gcc-7.4.0-1.x86_64/src/gcc-7.4.0
--prefix=/usr --exec-prefix=/usr --localstatedir=/var --sysconfdir=/etc
--docdir=/usr/share/doc/gcc --htmldir=/usr/share/doc/gcc/html -C
--build=x86_64-pc-cygwin --host=x86_64-pc-cygwin --target=x86_64-pc-cygwin
--without-libiconv-prefix --without-libintl-prefix --libexecdir=/usr/lib
--enable-shared --enable-shared-libgcc --enable-static
--enable-version-specific-runtime-libs --enable-bootstrap --enable-__cxa_atexit
--with-dwarf2 --with-tune=generic
--enable-languages=ada,c,c++,fortran,lto,objc,obj-c++ --enable-graphite
--enable-threads=posix --enable-libatomic --enable-libcilkrts --enable-libgomp
--enable-libitm --enable-libquadmath --enable-libquadmath-support
--disable-libssp --enable-libada --disable-symvers --with-gnu-ld --with-gnu-as
--with-cloog-include=/usr/include/cloog-isl --without-libiconv-prefix
--without-libintl-prefix --with-system-zlib --enable-linker-build-id
--with-default-libstdcxx-abi=gcc4-compatible --enable-libstdcxx-filesystem-ts
Thread model: posix
gcc version 7.4.0 (GCC)

Reply via email to