commit:     f02e644a90dde960b47f9bc87125fe37dece7ee9
Author:     Mike Frysinger <vapier <AT> gentoo <DOT> org>
AuthorDate: Sat Dec 19 18:04:40 2015 +0000
Commit:     Mike Frysinger <vapier <AT> gentoo <DOT> org>
CommitDate: Sat Dec 19 18:04:40 2015 +0000
URL:        https://gitweb.gentoo.org/proj/sandbox.git/commit/?id=f02e644a

libsandbox: tweak edge cases of realloc a bit

We need to return NULL when passed a size of 0 as the API requires the
return value be usable w/free, but we just freed the pointer so the ret
will cause memory corruption later on.

When we go to preserve the old content, we don't need the MIN check as
we already verified that a few lines up.  But leave it for defensive
purposes as gcc already optimizes it out for us.  Just comment things.

Signed-off-by: Mike Frysinger <vapier <AT> gentoo.org>

 libsandbox/memory.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/libsandbox/memory.c b/libsandbox/memory.c
index a2d69a2..a8f4d4b 100644
--- a/libsandbox/memory.c
+++ b/libsandbox/memory.c
@@ -81,7 +81,7 @@ void *realloc(void *ptr, size_t size)
                return malloc(size);
        if (size == 0) {
                free(ptr);
-               return ptr;
+               return NULL;
        }
 
        old_malloc_size = SB_MALLOC_TO_SIZE(ptr);
@@ -91,6 +91,10 @@ void *realloc(void *ptr, size_t size)
        ret = malloc(size);
        if (!ret)
                return ret;
+       /* We already verified old_malloc_size is smaller than size above, so
+        * we don't really need the MIN() here.  We leave it to be defensive,
+        * and because gcc optimizes away the check for us.
+        */
        memcpy(ret, ptr, MIN(size, old_malloc_size));
        free(ptr);
        return ret;

Reply via email to