1 /*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <string.h>
19 #include <search.h>
20 #include <time.h>
21 #include "test.h"
22
23 #define ARRAY_SIZE (10)
24 static void *root = NULL;
25 static int g_free_calls = 0;
26
malloc_node(unsigned n)27 void *malloc_node(unsigned n)
28 {
29 void *p;
30 p = malloc(n);
31 if (p) {
32 return p;
33 }
34 fprintf(stderr, "insufficient memory\n");
35 exit(EXIT_FAILURE);
36 }
37
cmp_node(const void * pa,const void * pb)38 int cmp_node(const void *pa, const void *pb)
39 {
40 if (*(int *)pa < *(int *)pb) {
41 return -1;
42 }
43 if (*(int *)pa > *(int *)pb) {
44 return 1;
45 }
46 return 0;
47 }
48
node_free(void * p)49 void node_free(void *p)
50 {
51 free(p);
52 g_free_calls++;
53 }
54
55 /**
56 * @tc.name : tdestroy_0100
57 * @tc.desc : Removes the whole tree pointed to by root
58 * @tc.level : Level 0
59 */
tdestroy_0100(void)60 void tdestroy_0100(void)
61 {
62 int i, *ptr, *target;
63 void *val, *result;
64 int array[ARRAY_SIZE] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
65
66 for (i = 0; i < ARRAY_SIZE; i++) {
67 ptr = malloc_node(sizeof(int));
68 *ptr = array[i];
69 val = tsearch((void *)ptr, &root, cmp_node);
70 if (val == NULL) {
71 exit(EXIT_FAILURE);
72
73 } else if ((*(int **)val) != ptr) {
74 free(ptr);
75 }
76 }
77
78 tdestroy(root, node_free);
79 if (g_free_calls != ARRAY_SIZE) {
80 t_error("%s tdestroy failed, g_free_calls is %d\n", __func__, g_free_calls);
81 }
82 }
83
main(int argc,char * argv[])84 int main(int argc, char *argv[])
85 {
86 tdestroy_0100();
87 return t_status;
88 }