Re: N3322 functionality tests

Bruno Haible via Gnulib discussion list <[email protected]>
Newsgroups gmane.comp.lib.gnulib.bugs
Message-ID <4110680.2vfOZ694Ok@cagnes>
Lasse Collin wrote on 2026-08-03:
> (Actually, memmove(NULL, ptr, 0) executes ptr <
> NULL, which is still undefined. It's an obsolete module though.)

Fixing it like this:


2026-08-15  Bruno Haible  <[email protected]>

	memmove: Avoid undefined behaviour upon memmove (NULL, ptr, 0).
	Reported by Lasse Collin in
	<https://lists.gnu.org/archive/html/bug-gnulib/2026-08/msg00096.html>.
	* lib/memmove.c (memmove): Test for length==0 case early.

diff --git a/lib/memmove.c b/lib/memmove.c
index 0d80de69c2..e7b17f6335 100644
--- a/lib/memmove.c
+++ b/lib/memmove.c
@@ -12,17 +12,26 @@
 void *
 memmove (void *dest0, void const *source0, size_t length)
 {
-  char *dest = dest0;
-  char const *source = source0;
-  if (source < dest)
-    /* Moving from low mem to hi mem; start at end.  */
-    for (source += length, dest += length; length; --length)
-      *--dest = *--source;
-  else if (source != dest)
+  if (length > 0)
     {
-      /* Moving from hi mem to low mem; start at beginning.  */
-      for (; length; --length)
-        *dest++ = *source++;
+      char *dest = dest0;
+      char const *source = source0;
+      if (source < dest)
+        {
+          /* Moving from low mem to hi mem; start at end.  */
+          source += length;
+          dest += length;
+          do
+            *--dest = *--source;
+          while (--length > 0);
+        }
+      else if (source != dest)
+        {
+          /* Moving from hi mem to low mem; start at beginning.  */
+          do
+            *dest++ = *source++;
+          while (--length > 0);
+        }
     }
   return dest0;
 }
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.