]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/test/test-alloc-util.c
23f008aeb9e350129b6adddb561c6d35375a6315
[thirdparty/systemd.git] / src / test / test-alloc-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 Copyright 2010 Lennart Poettering
4 ***/
5
6 #include <stdint.h>
7
8 #include "alloc-util.h"
9 #include "macro.h"
10 #include "util.h"
11
12 static void test_alloca(void) {
13 static const uint8_t zero[997] = { };
14 char *t;
15
16 t = alloca_align(17, 512);
17 assert_se(!((uintptr_t)t & 0xff));
18 memzero(t, 17);
19
20 t = alloca0_align(997, 1024);
21 assert_se(!((uintptr_t)t & 0x1ff));
22 assert_se(!memcmp(t, zero, 997));
23 }
24
25 static void test_memdup_multiply_and_greedy_realloc(void) {
26 int org[] = {1, 2, 3};
27 _cleanup_free_ int *dup;
28 int *p;
29 size_t i, allocated = 3;
30
31 dup = (int*) memdup_suffix0_multiply(org, sizeof(int), 3);
32 assert_se(dup);
33 assert_se(dup[0] == 1);
34 assert_se(dup[1] == 2);
35 assert_se(dup[2] == 3);
36 assert_se(*(uint8_t*) (dup + 3) == (uint8_t) 0);
37 free(dup);
38
39 dup = (int*) memdup_multiply(org, sizeof(int), 3);
40 assert_se(dup);
41 assert_se(dup[0] == 1);
42 assert_se(dup[1] == 2);
43 assert_se(dup[2] == 3);
44
45 p = dup;
46 assert_se(greedy_realloc0((void**) &dup, &allocated, 2, sizeof(int)) == p);
47
48 p = (int *) greedy_realloc0((void**) &dup, &allocated, 10, sizeof(int));
49 assert_se(p == dup);
50 assert_se(allocated >= 10);
51 assert_se(p[0] == 1);
52 assert_se(p[1] == 2);
53 assert_se(p[2] == 3);
54 for (i = 3; i < allocated; i++)
55 assert_se(p[i] == 0);
56 }
57
58 static void test_bool_assign(void) {
59 bool b, c, *cp = &c, d, e, f, g, h;
60
61 b = 123;
62 *cp = -11;
63 d = 0xF & 0xFF;
64 e = b & d;
65 f = 0x0;
66 g = cp; /* cast from pointer */
67 h = NULL; /* cast from pointer */
68
69 assert(b);
70 assert(c);
71 assert(d);
72 assert(e);
73 assert(!f);
74 assert(g);
75 assert(!h);
76 }
77
78 int main(int argc, char *argv[]) {
79 test_alloca();
80 test_memdup_multiply_and_greedy_realloc();
81 test_bool_assign();
82
83 return 0;
84 }