cmocka: realloc(ptr, 0) should act as free(ptr)
authorNiels de Vos <ndevos@redhat.com>
Thu, 26 Feb 2015 20:47:03 +0000 (21:47 +0100)
committerAndreas Schneider <asn@cryptomilk.org>
Mon, 2 Mar 2015 09:16:22 +0000 (10:16 +0100)
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@redhat.com>
Reviewed-by: Andreas Schneider <asn@cryptomilk.org>
Reviewed-by: Jakub Hrozek <jakub.hrozek@posteo.se>
src/cmocka.c
tests/test_alloc.c

index 9d3e704..c8e612c 100644 (file)
@@ -1676,6 +1676,7 @@ void *_test_realloc(void *ptr,
     }
 
     if (size == 0) {
+        _test_free(ptr, file, line);
         return NULL;
     }
 
index babe3a8..966814a 100644 (file)
@@ -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);