Bug 84474 - Unexpected -Wstringop-truncation on strncpy with string literal
Summary: Unexpected -Wstringop-truncation on strncpy with string literal
Status: RESOLVED WONTFIX
Alias: None
Product: gcc
Classification: Unclassified
Component: tree-optimization (show other bugs)
Version: 8.0.1
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords: diagnostic
Depends on:
Blocks: Wstringop-truncation
  Show dependency treegraph
 
Reported: 2018-02-20 01:39 UTC by Romain Geissler
Modified: 2019-01-09 23:46 UTC (History)
1 user (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Romain Geissler 2018-02-20 01:39:32 UTC
Hi,

When migrating some code base to gcc 8, I am hitting an issue on this snippet:

<<EOF
#include <string.h>

void f()
{
    char aBuf[3 + 1];
    strncpy(aBuf, "123", 3);
    aBuf[3] = '\0';
}
EOF

compiled with: -Wall -Werror -Wextra -std=gnu++17

I get:
error: ‘char* strncpy(char*, const char*, size_t)’ output truncated before terminating nul copying 3 bytes from a string of the same length [-Werror=stringop-truncation]

Here there is really nothing wrong in using strncpy. You might argue that here using strncpy is useless, while memcpy would simply do the trick. This is true, but this was extracted from a bigger code base where using strncpy actually makes sense ("123" is not hardcoded but is a user provided pointer, that gcc is clever enough to inline with -O2, thus hitting the very same error).

Cheers,
Romain
Comment 1 Martin Sebor 2018-02-20 03:04:51 UTC
This is among the unavoidable cases I was referring to in bug 84468.   The strcpy call with constant arguments is folded into memcpy too early to see the subsequent assignment of the NUL.  I argued to defer this early folding because it tends to defeat downstream optimizations but I lost.

I would make the argument (and have) that in the test case, strncpy is being misused and strcpy (or other string functions if strcpy is not acceptable) would be more appropriate.

If you have a test case with the inlining please open a new bug.  It may not get fixed for GCC 8 but it might serve as an argument for deferring folding these calls until more context is available, or for other solutions.