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