GCC 8 added a -Wstringop-truncation
warning. From https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82944 :
The -Wstringop-truncation warning added in GCC 8.0 via r254630 for bug 81117 is specifically intended to highlight likely unintended uses of the strncpy function that truncate the terminating NUL charcter from the source string. An example of such a misuse given in the request is the following:
char buf[2];
void test (const char* str)
{
strncpy (buf, str, strlen (str));
}
I get the same warning with this code.
strncpy(this->name, name, 32);
warning: 'char* strncpy(char*, const char*, size_t)' specified bound 32 equals destination size [-Wstringop-truncation`]
Considering that this->name
is char name[32]
and name
is a char*
with a length potentially greater than 32. I would like to copy name
into this->name
and truncate it if it is greater than 32. Should size_t
be 31 instead of 32? I'm confused. It is not mandatory for this->name
to be NUL-terminated.