>From d44241344e8455c59ea04440706cfaf72862c404 Mon Sep 17 00:00:00 2001 From: Bruno Haible Date: Sat, 6 Jul 2019 00:47:12 +0200 Subject: [PATCH 5/5] 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. --- ChangeLog | 7 +++++++ lib/getcwd-lgpl.c | 13 +++++++++---- lib/getcwd.c | 2 +- 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/ChangeLog b/ChangeLog index 1f5f18b..98d5531 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,5 +1,12 @@ 2019-07-05 Bruno Haible + 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 + xgetdomainname: Don't return an excessive memory allocation. * lib/xgetdomainname.c (xgetdomainname): Shrink the domainname buffer before returning it. diff --git a/lib/getcwd-lgpl.c b/lib/getcwd-lgpl.c index b224cfc..1eaac78 100644 --- a/lib/getcwd-lgpl.c +++ b/lib/getcwd-lgpl.c @@ -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; } diff --git a/lib/getcwd.c b/lib/getcwd.c index 8f15f56..bf87809 100644 --- a/lib/getcwd.c +++ b/lib/getcwd.c @@ -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 -- 2.7.4