gbranden pushed a commit to branch master
in repository groff.

commit cde7dc97696a494510e06f1315756b524cb846d7
Author: G. Branden Robinson <[email protected]>
AuthorDate: Sat Jun 20 05:09:33 2026 -0500

    [libgroff]: Improve `string` reallocations. (1/2)
    
    * src/libs/libgroff/string.cpp (srealloc): Avoid unnecessary memset(3)
      if the new string's `length` is equal to the old string's `sz`
      (capacity), because it is already (invariantly) null-terminated.
      Simplify condition for performing memcpy(3) of old contents to new: do
      it only if the old length is not zero.  Unconditionally memset(3) the
      memory from the end of the new string to the end of string's capacity.
---
 ChangeLog                    | 10 ++++++++++
 src/libs/libgroff/string.cpp |  9 ++++-----
 2 files changed, 14 insertions(+), 5 deletions(-)

diff --git a/ChangeLog b/ChangeLog
index bbd0598ff..a7c784034 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,13 @@
+2026-06-20  G. Branden Robinson <[email protected]>
+
+       * src/libs/libgroff/string.cpp (srealloc): Avoid unnecessary
+       memset(3) if the new string's `length` is equal to the old
+       string's `sz` (capacity), because it is already (invariantly)
+       null-terminated.  Simplify condition for performing memcpy(3) of
+       old contents to new: do it only if the old length is not zero.
+       Unconditionally memset(3) the memory from the end of the new
+       string to the end of string's capacity.
+
 2026-06-19  G. Branden Robinson <[email protected]>
 
        * src/libs/libgroff/string.cpp (string::string): Drop redundant
diff --git a/src/libs/libgroff/string.cpp b/src/libs/libgroff/string.cpp
index 731aa4887..227357b26 100644
--- a/src/libs/libgroff/string.cpp
+++ b/src/libs/libgroff/string.cpp
@@ -99,7 +99,8 @@ static char *srealloc(char *ptr, size_t oldsz, size_t oldlen,
 {
   if (oldsz >= newlen) {
     *sizep = oldsz;
-    memset((ptr + oldlen), 0, (newlen - oldsz));
+    if (oldsz > newlen)
+      memset((ptr + newlen), 0, (oldsz - newlen));
     return ptr;
   }
   size_t amount = newlen;
@@ -117,11 +118,9 @@ static char *srealloc(char *ptr, size_t oldsz, size_t 
oldlen,
   catch (const std::bad_alloc &exc) {
     fatal("cannot allocate %1 bytes for string reallocation", amount);
   }
-  if ((oldlen < newlen) && (oldlen != 0)) {
-    assert(amount > 0);
-    memset(p, 0, amount);
+  if (oldlen != 0)
     memcpy(p, ptr, oldlen);
-  }
+  memset((p + oldlen), 0, (amount - oldlen));
   delete[] ptr;
   return p;
 }

_______________________________________________
groff-commit mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/groff-commit

Reply via email to