Mon, 01 Mar 2021 22:19:06 +0100
adds cxReallocate()
src/allocator.c | file | annotate | diff | comparison | revisions | |
src/cx/allocator.h | file | annotate | diff | comparison | revisions | |
test/test_allocator.c | file | annotate | diff | comparison | revisions |
--- 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 <stdlib.h> +#include <errno.h> 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); }
--- 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);
--- 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();