Bug 96296 - libiberty/dyn-string.c:280:3: warning: ‘strncpy’ output truncated before terminating nul copying as many bytes from a string as its length [-Wstringop-truncation]
Summary: libiberty/dyn-string.c:280:3: warning: ‘strncpy’ output truncated before term...
Status: UNCONFIRMED
Alias: None
Product: gcc
Classification: Unclassified
Component: tree-optimization (show other bugs)
Version: 11.0
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords: diagnostic
Depends on:
Blocks: Wstringop-truncation
  Show dependency treegraph
 
Reported: 2020-07-23 08:06 UTC by Tom de Vries
Modified: 2022-10-23 00:21 UTC (History)
3 users (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 Tom de Vries 2020-07-23 08:06:58 UTC
[ Reported and discussed earlier here: https://gcc.gnu.org/legacy-ml/gcc/2019-03/msg00184.html ]

I ran into this warning in dyn-string.c:
...
$ gcc-11 src/libiberty/dyn-string.c -I src/include/ -c -DHAVE_STRING_H -DHAVE_STDLIB_H  -Wall -O2
src/libiberty/dyn-string.c: In function ‘dyn_string_insert_cstr’:
src/libiberty/dyn-string.c:280:3: warning: ‘strncpy’ output truncated before terminating nul copying as many bytes from a string as its length [-Wstringop-truncation]
  280 |   strncpy (dest->s + pos, src, length);
      |   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/libiberty/dyn-string.c:272:16: note: length computed here
  272 |   int length = strlen (src);
      |                ^~~~~~~~~~~~
...

As mentioned here ( https://gcc.gnu.org/legacy-ml/gcc/2019-03/msg00199.html ): "Using memcpy instead of strncpy would avoid the warning".

Tentative untested patch fixes the warning:
...
diff --git a/libiberty/dyn-string.c b/libiberty/dyn-string.c
index e10f691181a..bf155effb5f 100644
--- a/libiberty/dyn-string.c
+++ b/libiberty/dyn-string.c
@@ -277,7 +277,7 @@ dyn_string_insert_cstr (dyn_string_t dest, int pos, const char *sr
c)
   for (i = dest->length; i >= pos; --i)
     dest->s[i + length] = dest->s[i];
   /* Splice in the new stuff.  */
-  strncpy (dest->s + pos, src, length);
+  memcpy (dest->s + pos, src, length);
   /* Compute the new length.  */
   dest->length += length;
   return 1;
...