From: Nathan Moinvaziri Date: Mon, 14 Mar 2022 18:46:02 +0000 (-0700) Subject: Added unit test for zng_calloc_aligned to ensure that it always returns 64-byte align... X-Git-Tag: 2.1.0-beta1~347 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=87b4a35b7a71fd34542dd2ca75c54bd0b7000385;p=thirdparty%2Fzlib-ng.git Added unit test for zng_calloc_aligned to ensure that it always returns 64-byte aligned memory allocation when requested. --- diff --git a/test/test_aligned_alloc.cc b/test/test_aligned_alloc.cc new file mode 100644 index 00000000..43324d3d --- /dev/null +++ b/test/test_aligned_alloc.cc @@ -0,0 +1,44 @@ +/* test_aligned_alloc.cc - Test zng_calloc_aligned and zng_cfree_aligned */ + +#include +#include +#include + +extern "C" { +# include "zbuild.h" +# include "zutil.h" +} + +#include + +void *zng_calloc_unaligned(void *opaque, unsigned items, unsigned size) { + uint8_t *pointer = (uint8_t *)calloc(1, (items * size) + 2); + if (pointer == NULL) + return pointer; + /* Store whether or not our allocation is aligned */ + *pointer = ((uint64_t)(intptr_t)pointer + 1) % 2 == 0; + pointer++; + if (*pointer) { + /* Return pointer that is off by one */ + pointer++; + } + return (void *)pointer; +} + +void zng_cfree_unaligned(void *opaque, void *ptr) { + uint8_t *pointer = (uint8_t *)ptr; + pointer--; + /* Get whether or not our original memory pointer was aligned */ + if (*pointer) { + /* Return original aligned pointer to free() */ + pointer--; + } + free(pointer); +} + +TEST(zalloc, aligned_64) { + void *return_ptr = zng_calloc_aligned(zng_calloc_unaligned, 0, 1, 100, 64); + ASSERT_TRUE(return_ptr != NULL); + EXPECT_EQ((intptr_t)return_ptr % 64, 0); + zng_cfree_aligned(zng_cfree_unaligned, 0, return_ptr); +}