[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[PATCH] realloc(ptr, 0) should act as free(ptr)


Currently, realloc(ptr, 0) does not free the pointer as specified by
'man 3 realloc':

    The realloc() function changes the size of the memory block pointed
    to by ptr to size bytes. [...] if size is equal to zero, and ptr is
    not NULL, then the call is equivalent to free(ptr). [...]

This causes a leak of the allocated memory, and tests that use this
particular realloc() pattern fail.

Signed-off-by: Niels de Vos <ndevos@xxxxxxxxxx>
---
 src/cmocka.c       |  1 +
 tests/test_alloc.c | 17 +++++++++++++++++
 2 files changed, 18 insertions(+)

diff --git a/src/cmocka.c b/src/cmocka.c
index 9d3e704..c8e612c 100644
--- a/src/cmocka.c
+++ b/src/cmocka.c
@@ -1676,6 +1676,7 @@ void *_test_realloc(void *ptr,
     }
 
     if (size == 0) {
+        _test_free(ptr, file, line);
         return NULL;
     }
 
diff --git a/tests/test_alloc.c b/tests/test_alloc.c
index babe3a8..966814a 100644
--- a/tests/test_alloc.c
+++ b/tests/test_alloc.c
@@ -64,10 +64,27 @@ static void torture_test_realloc(void **state)
     test_free(str);
 }
 
+static void torture_test_realloc_set0(void **state)
+{
+    char *str;
+    size_t str_len;
+
+    (void)state; /* unsused */
+
+    str_len = 16;
+    str = (char *)test_malloc(str_len);
+    assert_non_null(str);
+
+    /* realloc(ptr, 0) is like a free() */
+    str = (char *)test_realloc(str, 0);
+    assert_null(str);
+}
+
 int main(void) {
     const struct CMUnitTest alloc_tests[] = {
         cmocka_unit_test(torture_test_malloc),
         cmocka_unit_test(torture_test_realloc),
+        cmocka_unit_test(torture_test_realloc_set0),
     };
 
     return cmocka_run_group_tests(alloc_tests, NULL, NULL);
-- 
2.1.0