1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
|
///usr/bin/true; gcc -std=c2x -Wall -Wextra -Wpedantic -pedantic-errors -fanalyzer -Wanalyzer-too-complex -ggdb -g3 -O0 main.c -o main && ./main; exit $?
// #include <errno.h>
// #include <error.h>
// #include <stdio.h>
// #include <threads.h>
// #include <unistd.h>
// #include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
void * xcalloc(size_t nmemb, size_t size) {
void *mem = calloc(nmemb, size);
if(!mem)
abort();
return mem;
}
typedef void (*fcallback)(void*);
typedef struct gdata {
void *data;
fcallback freer;
} gdata;
gdata * gdata_init(void *data, fcallback fcb) {
gdata *gd = xcalloc(1, sizeof(*gd));
gd->data = data;
gd->freer = fcb;
return gd;
}
void gdata_free(gdata *gd) {
if(!gd)
return;
if(gd->freer != NULL)
gd->freer(gd->data);
free(gd);
return;
}
void * gdata_getdata(gdata * const gd) {
if(!gd) {
errno = EINVAL;
return NULL;
}
return gd->data;
}
void gdata_destruct(gdata *gd, void **storage) {
if(!gd || !storage)
return;
*storage = gd->data;
free(gd);
return;
}
typedef struct stack {
gdata **arr;
int size;
int used;
} stack;
stack * stack_init(int size) {
if(size < 1)
return NULL;
stack *st = xcalloc(1, sizeof(*st));
st->size = size;
st->used = 0;
st->arr = xcalloc(st->size, sizeof(gdata*));
return st;
}
void stack_free(stack *st) {
if(!st)
return;
for(int i = 0; i < st->used; i++)
gdata_free(st->arr[i]);
free(st->arr);
free(st);
return;
}
int stack_push(stack *st, gdata *data) {
if(!st || !data)
return -1;
if(st->used == st->size)
return 0;
st->arr[st->used++] = data;
return st->used;
}
int stack_pushd(stack *st, void *data, fcallback fcb) {
return stack_push(st, gdata_init(data, fcb));
}
gdata * stack_pop(stack *st) {
if(!st)
return NULL;
if(st->used <= 0)
return NULL;
gdata *gd = st->arr[--st->used];
return gd;
}
void * stack_popd(stack *st) {
gdata *gd = stack_pop(st);
void *data = NULL;
gdata_destruct(gd, &data);
return data;
}
int main() {
// stack *st = stack_init(10);
// stack_pushd(st, (void*)10, NULL);
// stack_pushd(st, (void*)11, NULL);
// stack_pushd(st, (void*)12, NULL);
// stack_pushd(st, strdup("This is some data"), free);
// char *data = stack_popd(st);
// printf("%s\n", (data) ? data : "null");
// free(data);
// stack_free(st);
return 0;
}
|