# HG changeset patch # User Mike Becker # Date 1614633546 -3600 # Node ID 81a4c3a63e655cc60ddf4c6e4d07fcbb9ca45a44 # Parent 0f4aa9fc75d961a4de33f6c844235c967fed03d8 adds cxReallocate() diff -r 0f4aa9fc75d9 -r 81a4c3a63e65 src/allocator.c --- a/src/allocator.c Sun Feb 14 15:37:12 2021 +0100 +++ b/src/allocator.c Mon Mar 01 22:19:06 2021 +0100 @@ -29,6 +29,7 @@ #include "cx/allocator.h" #include +#include void *cx_malloc_stdlib(void *unused, size_t n) { return malloc(n); @@ -67,6 +68,20 @@ return allocator->cl->realloc(allocator->data, mem, n); } +int cxReallocate(CxAllocator allocator, void **mem, size_t n) { + if (mem == NULL) { + errno = EINVAL; + return 1; + } + void* nmem = allocator->cl->realloc(allocator->data, *mem, n); + if (nmem == NULL) { + return 1; + } else { + *mem = nmem; + return 0; + } +} + void *cxCalloc(CxAllocator allocator, size_t nelem, size_t n) { return allocator->cl->calloc(allocator->data, nelem, n); } diff -r 0f4aa9fc75d9 -r 81a4c3a63e65 src/cx/allocator.h --- a/src/cx/allocator.h Sun Feb 14 15:37:12 2021 +0100 +++ b/src/cx/allocator.h Mon Mar 01 22:19:06 2021 +0100 @@ -52,6 +52,8 @@ void *cxRealloc(CxAllocator allocator, void *mem, size_t n); +int cxReallocate(CxAllocator allocator, void **mem, size_t n); + void *cxCalloc(CxAllocator allocator, size_t nelem, size_t n); void cxFree(CxAllocator allocator, void *mem); diff -r 0f4aa9fc75d9 -r 81a4c3a63e65 test/test_allocator.c --- a/test/test_allocator.c Sun Feb 14 15:37:12 2021 +0100 +++ b/test/test_allocator.c Mon Mar 01 22:19:06 2021 +0100 @@ -49,6 +49,21 @@ free(test); } +void test_default_reallocate(void) { + void *test = calloc(8, 1); + memcpy(test, "Test", 4); + int rval = cxReallocate(cxDefaultAllocator, &test, 16); + CU_ASSERT_EQUAL(rval, 0); + CU_ASSERT_PTR_NOT_NULL(test) + CU_ASSERT_STRING_EQUAL("Test", test) + free(test); +} + +void test_reallocate_null(void) { + int rval = cxReallocate(cxDefaultAllocator, NULL, 16); + CU_ASSERT_EQUAL(rval, EINVAL); +} + void test_default_calloc(void) { void *test = cxCalloc(cxDefaultAllocator, 8, 2); CU_ASSERT_PTR_NOT_NULL(test) @@ -78,7 +93,9 @@ !CU_add_test(suite, "default allocator available", test_default_allocator_available) || !CU_add_test(suite, "test of malloc()", test_default_malloc)|| !CU_add_test(suite, "test of realloc()", test_default_realloc) || - !CU_add_test(suite, "test of realloc()", test_default_calloc) || + !CU_add_test(suite, "test of realloc() via cxReallocate", test_default_reallocate) || + !CU_add_test(suite, "test of cxReallocate with NULL", test_default_reallocate) || + !CU_add_test(suite, "test of calloc()", test_default_calloc) || !CU_add_test(suite, "test of free()", test_default_free) ) { CU_cleanup_registry();