https://gcc.gnu.org/bugzilla/show_bug.cgi?id=100842
Bug ID: 100842
Summary: Invalid -Wstringop-truncation with strncat and -O2
Product: gcc
Version: 11.1.1
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c
Assignee: unassigned at gcc dot gnu.org
Reporter: cerrigno at gmail dot com
Target Milestone: ---
Created attachment 50899
--> https://gcc.gnu.org/bugzilla/attachment.cgi?id=50899&action=edit
Test source code
I have the following code
////
#include <string.h>
char last_str[4];
void copy_strncat(const char *str) {
last_str[0] = '\0';
strncat(last_str, str, sizeof(last_str) - 1);
}
void copy_strncpy(const char *str) {
strncpy(last_str, str, sizeof(last_str));
last_str[sizeof(last_str) - 1] = '\0';
}
void test() {
char str[] = "test";
copy_strncat(str);
copy_strncpy(str);
}
////
If compiled with "-O2 -Wall" on GCC 11 (tested since GCC 8.1) I get an invalid
warning only in the strncat version the copy function, even if both are safe
and perform (almost) the same thing:
warning: 'strncat' output truncated copying 3 bytes from a string of length 4
[-Wstringop-truncation]
strncat(last_str, str, sizeof(last_str) - 1);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In the strncpy version, the -Wstringop-truncation warning is disarmed by the
null terminator assignment after strncpy. I would expect the same from the
assignment made before strncat.
Here you may find my test in godbolt: https://godbolt.org/z/zEaczYzja