strerror_r-posix: memmove, not memcpy
authorPaul Eggert <eggert@cs.ucla.edu>
Thu, 29 Nov 2018 00:10:03 +0000 (16:10 -0800)
committerPaul Eggert <eggert@cs.ucla.edu>
Thu, 29 Nov 2018 00:10:51 +0000 (16:10 -0800)
* lib/strerror_r.c (safe_copy): Use memmove, not memcpy,
since the source and destination might overlap in the call
‘safe_copy (buf, buflen, strerror_r (errnum, buf, buflen))’.
Simplify.

ChangeLog
lib/strerror_r.c

index 681603031238375273e83b411200f1f45a86b90a..aec0ac21b185b7315550bd45f3ecac407d7c4b9d 100644 (file)
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,11 @@
+2018-11-28  Paul Eggert  <eggert@cs.ucla.edu>
+
+       strerror_r-posix: memmove, not memcpy
+       * lib/strerror_r.c (safe_copy): Use memmove, not memcpy,
+       since the source and destination might overlap in the call
+       ‘safe_copy (buf, buflen, strerror_r (errnum, buf, buflen))’.
+       Simplify.
+
 2018-11-25  Akim Demaille  <akim@lrde.epita.fr>
 
        bitsetv: new module
index 7a11be1cafa3239e34749ef79dfecaf5073b9d01..2a22cb41466327d730256d5c883684f19852c385 100644 (file)
@@ -129,22 +129,13 @@ static int
 safe_copy (char *buf, size_t buflen, const char *msg)
 {
   size_t len = strlen (msg);
-  int ret;
+  size_t moved = len < buflen ? len : buflen - 1;
 
-  if (len < buflen)
-    {
-      /* Although POSIX allows memcpy() to corrupt errno, we don't
-         know of any implementation where this is a real problem.  */
-      memcpy (buf, msg, len + 1);
-      ret = 0;
-    }
-  else
-    {
-      memcpy (buf, msg, buflen - 1);
-      buf[buflen - 1] = '\0';
-      ret = ERANGE;
-    }
-  return ret;
+  /* Although POSIX lets memmove corrupt errno, we don't
+     know of any implementation where this is a real problem.  */
+  memmove (buf, msg, moved);
+  buf[moved] = '\0';
+  return len < buflen ? 0 : ERANGE;
 }