]> Savannah Git Hosting - gnulib.git/commitdiff
getcwd-lgpl, getcwd: Don't call realloc when it is pointless.
authorBruno Haible <bruno@clisp.org>
Fri, 5 Jul 2019 22:47:12 +0000 (00:47 +0200)
committerBruno Haible <bruno@clisp.org>
Fri, 5 Jul 2019 22:55:25 +0000 (00:55 +0200)
* lib/getcwd-lgpl.c (rpl_getcwd): Don't call realloc if the result's
needed size is equal to the allocated size.
* lib/getcwd.c (__getcwd): Likewise.

ChangeLog
lib/getcwd-lgpl.c
lib/getcwd.c

index 1f5f18b108a76d32e5447469f32883447c9d5c62..98d5531b1ca3c64f858bfa119b80ff02a771ae0b 100644 (file)
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,10 @@
+2019-07-05  Bruno Haible  <bruno@clisp.org>
+
+       getcwd-lgpl, getcwd: Don't call realloc when it is pointless.
+       * lib/getcwd-lgpl.c (rpl_getcwd): Don't call realloc if the result's
+       needed size is equal to the allocated size.
+       * lib/getcwd.c (__getcwd): Likewise.
+
 2019-07-05  Bruno Haible  <bruno@clisp.org>
 
        xgetdomainname: Don't return an excessive memory allocation.
index b224cfc9d109ce0d715e66d7a07e872d748277bf..1eaac78b541c14053e8c8daadec02672641f7eb5 100644 (file)
@@ -115,10 +115,15 @@ rpl_getcwd (char *buf, size_t size)
     }
   else
     {
-      /* Trim to fit, if possible.  */
-      result = realloc (buf, strlen (buf) + 1);
-      if (!result)
-        result = buf;
+      /* Here result == buf.  */
+      /* Shrink result before returning it.  */
+      size_t actual_size = strlen (result) + 1;
+      if (actual_size < size)
+        {
+          char *shrinked_result = realloc (result, actual_size);
+          if (shrinked_result != NULL)
+            result = shrinked_result;
+        }
     }
   return result;
 }
index 8f15f560c28a83e7244e9a4483543a7029bf251c..bf878092a5670e31a5a06402dbdccb703120b53d 100644 (file)
@@ -443,7 +443,7 @@ __getcwd (char *buf, size_t size)
 
   if (size == 0)
     /* Ensure that the buffer is only as large as necessary.  */
-    buf = realloc (dir, used);
+    buf = (used < allocated ? realloc (dir, used) : dir);
 
   if (buf == NULL)
     /* Either buf was NULL all along, or 'realloc' failed but