https://gcc.gnu.org/bugzilla/show_bug.cgi?id=84480
Bug ID: 84480 Summary: Unexpected -Wstringop-truncation on strncpy with string literal at -O2 Product: gcc Version: 8.0.1 Status: UNCONFIRMED Severity: normal Priority: P3 Component: tree-optimization Assignee: unassigned at gcc dot gnu.org Reporter: romain.geissler at amadeus dot com Target Milestone: --- Hi, As required in PR 84474, here is a more real life example of unexpected -Wstringop-truncation. Let's consider a special string implementation that would use the fact that the string length can be bounded to a given limit. This would be a templated class (so visible to other translation units, and thus optimizable through inlining and constant propagation). <<EOF #include <string.h> template <size_t N> class String { public: String(const char* iString, size_t iStringLength = N) { if (iStringLength > N) { iStringLength = N; } strncpy(_cstring, iString, iStringLength); _cstring[iStringLength] = '\0'; } private: char _cstring[N + 1]; }; void f(const char* iUserProvidedString) { String<3> aString1("12"); // No warning String<3> aString2("123"); // Warning String<3> aString3(iUserProvidedString); // Warning here if g is uncommented. } void g() { f("456"); } compiled with: -Wall -Werror -Wextra -std=gnu++17 -O2 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] for string "123" and "456". I don't know if you can do anything in that case. Actually I still haven't understood what this particular warning would prevent me from doing. Does gcc fears that I don't null terminate _cstring ? Shouldn't the fact that the next statement actually null terminates _cstring be enough to silence the warning ? Cheers, Romain