[2/2] libm/stdlib: Realloc when shrinking by 2* or more

Message ID 20200814001902.510489-3-keithp@keithp.com
State Accepted
Commit 8a7ec55c535cddd74d45a2f6fb644ecded114de8
Headers show
Series
  • Realloc fixes version 2
Related show

Commit Message

Eshan dhawan via Newlib Aug. 14, 2020, 12:19 a.m.
This reduces memory usage when reallocating objects much smaller.

Signed-off-by: Keith Packard <keithp@keithp.com>

---
 newlib/libc/stdlib/nano-mallocr.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

-- 
2.28.0

Patch

diff --git a/newlib/libc/stdlib/nano-mallocr.c b/newlib/libc/stdlib/nano-mallocr.c
index 5028431ec..d178c34ab 100644
--- a/newlib/libc/stdlib/nano-mallocr.c
+++ b/newlib/libc/stdlib/nano-mallocr.c
@@ -476,15 +476,15 @@  void * nano_realloc(RARG void * ptr, malloc_size_t size)
         return NULL;
     }
 
-    /* TODO: There is chance to shrink the chunk if newly requested
-     * size is much small */
     old_size = nano_malloc_usable_size(RCALL ptr);
-    if (old_size >= size)
+    if (size <= old_size && (old_size >> 1) < size)
       return ptr;
 
     mem = nano_malloc(RCALL size);
     if (mem != NULL)
     {
+	if (old_size > size)
+	    old_size = size;
         memcpy(mem, ptr, old_size);
         nano_free(RCALL ptr);
     }