https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85598
Bug ID: 85598 Summary: Incorrect warning only at -O2 and -O3 Product: gcc Version: 7.3.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c Assignee: unassigned at gcc dot gnu.org Reporter: thomas.mercier.jr at gmail dot com Target Milestone: --- Created attachment 44049 --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=44049&action=edit Preprocessed file of program that reproduces the behavior $ gcc -v Using built-in specs. COLLECT_GCC=x86_64-pc-linux-gnu-gcc COLLECT_LTO_WRAPPER=/brazil-pkg-cache/packages/GCC/GCC-7.x.200154.0/AL2012/DEV.STD.PTHREAD/build/gcc-7.3.0/bin/../libexec/gcc/x86_64-pc-linux-gnu/7.3.0/lto-wrapper Target: x86_64-pc-linux-gnu Configured with: /local/p4clients/pkgbuild-Kfsa6/workspace/src/GCC/build/private/src/gcc-7.3.0/configure --prefix=/local/p4clients/pkgbuild-Kfsa6/workspace/src/GCC/build/gcc-7.3.0 --enable-languages=c,c++,fortran --disable-plugin --with-build-config=bootstrap-lto --with-gmp=/local/p4clients/pkgbuild-Kfsa6/workspace/src/GCC/build/private/stage2 --with-mpfr=/local/p4clients/pkgbuild-Kfsa6/workspace/src/GCC/build/private/stage2 --with-mpc=/local/p4clients/pkgbuild-Kfsa6/workspace/src/GCC/build/private/stage2 --with-fpmath=sse --with-cpu-64=core2 --disable-multilib --disable-bootstrap --with-glibc-version=2.12 --with-cloog=/local/p4clients/pkgbuild-Kfsa6/workspace/src/GCC/build/private/stage2 --with-ppl=/local/p4clients/pkgbuild-Kfsa6/workspace/src/GCC/build/private/stage2 --with-isl=/local/p4clients/pkgbuild-Kfsa6/workspace/src/GCC/build/private/stage2 --enable-libsanitizer --disable-stage1-checking Thread model: posix gcc version 7.3.0 (GCC) When compiled with -O2 or -O3 optimization enabled, the following warning is printed: $ gcc -Wall -O2 /tmp/test.c /tmp/test.c: In function ‘main’: /tmp/test.c:9:31: warning: ‘snprintf’ output may be truncated before the last format character [-Wformat-truncation=] snprintf(str, 4, "%%%02X", x); ^ /tmp/test.c:9:7: note: ‘snprintf’ output between 4 and 5 bytes into a destination of size 4 snprintf(str, 4, "%%%02X", x); ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~ With lesser levels of optimization, no warning is printed: $ gcc -Wall -O1 /tmp/test.c $ This is the entire program (preprocessed attached): #include <stdio.h> int main() { char temp[100]; unsigned int x; char *str = temp; for(x=0; x<256; ++x) { snprintf(str, 4, "%%%02X", x); } } Calling snprintf with NULL and 0 for the first two arguments returns 3 for all values of the loop. I believe the correct behavior from GCC is no warning at any optimization level.