1 /* test_aligned_alloc.cc - Test zng_alloc_aligned and zng_free_aligned */
2
3 #include <stdlib.h>
4 #include <errno.h>
5 #include <stdio.h>
6
7 extern "C" {
8 # include "zbuild.h"
9 # include "zutil.h"
10 }
11
12 #include <gtest/gtest.h>
13
zng_calloc_unaligned(void * opaque,unsigned items,unsigned size)14 void *zng_calloc_unaligned(void *opaque, unsigned items, unsigned size) {
15 uint8_t *pointer = (uint8_t *)calloc(1, (items * size) + 2);
16 Z_UNUSED(opaque);
17 if (pointer == NULL)
18 return pointer;
19 /* Store whether or not our allocation is aligned */
20 *pointer = ((uint64_t)(intptr_t)pointer + 1) % 2 == 0;
21 pointer++;
22 if (*pointer) {
23 /* Return pointer that is off by one */
24 pointer++;
25 }
26 return (void *)pointer;
27 }
28
zng_cfree_unaligned(void * opaque,void * ptr)29 void zng_cfree_unaligned(void *opaque, void *ptr) {
30 uint8_t *pointer = (uint8_t *)ptr;
31 Z_UNUSED(opaque);
32 pointer--;
33 /* Get whether or not our original memory pointer was aligned */
34 if (*pointer) {
35 /* Return original aligned pointer to free() */
36 pointer--;
37 }
38 free(pointer);
39 }
40
TEST(zalloc,aligned_64)41 TEST(zalloc, aligned_64) {
42 void *return_ptr = zng_alloc_aligned(zng_calloc_unaligned, 0, 1, 100, 64);
43 ASSERT_TRUE(return_ptr != NULL);
44 EXPECT_EQ((intptr_t)return_ptr % 64, 0);
45 zng_free_aligned(zng_cfree_unaligned, 0, return_ptr);
46 }
47