https://gcc.gnu.org/bugzilla/show_bug.cgi?id=107473
Bug ID: 107473 Summary: Unexpected warning / error with strncpy Product: gcc Version: 11.2.1 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c Assignee: unassigned at gcc dot gnu.org Reporter: lli at a10networks dot com Target Milestone: --- When I compile this source code, I hit -Werror=stringop-truncation. #include <string.h> #include <stdio.h> #include <limits.h> static char a[PATH_MAX]; static char b[PATH_MAX]; void my_test() { snprintf(b, sizeof(b), "/linux/path"); strncpy(a,b,sizeof(a)-1); } root:/sources# gcc -Wall -Werror -Wextra -O2 -c test4.c -o test4.o test4.c: In function 'my_test': test4.c:10:9: error: 'strncpy' output may be truncated copying 4095 bytes from a string of length 4095 [-Werror=stringop-truncation] 10 | strncpy(a,b,sizeof(a)-1); | ^~~~~~~~~~~~~~~~~~~~~~~~ cc1: all warnings being treated as errors If I compile same file without O2, there is no such issue. If I add '\0' to the end of a, there is no such issue. static char a[PATH_MAX]; static char b[PATH_MAX]; void my_test() { snprintf(b, sizeof(b), "/linux/path"); strncpy(a,b,sizeof(a)-1); a[sizeof(a)-1]='\0'; } If I add memset before strncpy, I hit the issue again. static char a[PATH_MAX]; static char b[PATH_MAX]; void my_test() { snprintf(b, sizeof(b), "/linux/path"); memset(a, 0, sizeof(a)); strncpy(a,b,sizeof(a)-1); a[sizeof(a)-1]='\0'; } root:/sources# gcc -Wall -Werror -Wextra -O2 -c test4.c -o test4.o test4.c: In function 'my_test': test4.c:11:9: error: 'strncpy' output may be truncated copying 4095 bytes from a string of length 4095 [-Werror=stringop-truncation] 11 | strncpy(a,b,sizeof(a)-1); | ^~~~~~~~~~~~~~~~~~~~~~~~ cc1: all warnings being treated as errors GCC info: root:/sources# gcc -v Using built-in specs. COLLECT_GCC=gcc COLLECT_LTO_WRAPPER=/usr/libexec/gcc/x86_64-redhat-linux/11/lto-wrapper OFFLOAD_TARGET_NAMES=nvptx-none OFFLOAD_TARGET_DEFAULT=1 Target: x86_64-redhat-linux Configured with: ../configure --enable-bootstrap --enable-host-pie --enable-host-bind-now --enable-languages=c,c++,fortran,lto --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla --enable-shared --enable-threads=posix --enable-checking=release --enable-multilib --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable-linker-build-id --with-gcc-major-version-only --with-linker-hash-style=gnu --enable-plugin --enable-initfini-array --without-isl --enable-offload-targets=nvptx-none --without-cuda-driver --enable-gnu-indirect-function --enable-cet --with-tune=generic --with-arch_64=x86-64-v2 --with-arch_32=x86-64 --build=x86_64-redhat-linux --with-build-config=bootstrap-lto --enable-link-serialization=1 Thread model: posix Supported LTO compression algorithms: zlib zstd gcc version 11.2.1 20220127 (Red Hat 11.2.1-9) (GCC)