1
2 #include <stdlib.h>
3 #include <stdint.h>
4 #include <assert.h>
5 #include <string.h>
6
7 #include "../memcheck.h"
8
9 struct cell
10 {
11 struct cell *next;
12 int x;
13 };
14
15 struct pool
16 {
17 size_t allocated;
18 size_t used;
19 uint8_t *buf;
20 };
21
22 void *
allocate_from_pool(struct pool * p,size_t n)23 allocate_from_pool(struct pool *p, size_t n)
24 {
25 void *a = p->buf + p->used;
26 assert(p->used + n < p->allocated);
27 VALGRIND_MEMPOOL_ALLOC(p, a, n);
28 p->used += n;
29 return a;
30 }
31
32 struct pool *
allocate_pool()33 allocate_pool()
34 {
35 struct pool *p = malloc(sizeof(struct pool));
36 assert(p);
37 p->allocated = 4096;
38 p->used = 0;
39 p->buf = malloc(p->allocated);
40 assert(p->buf);
41 memset(p->buf, 0, p->allocated);
42 VALGRIND_CREATE_MEMPOOL(p, 0, 0);
43 (void) VALGRIND_MAKE_MEM_NOACCESS(p->buf, p->allocated);
44 return p;
45 }
46
47 #define N 100
48
49 /* flags */
50 int static_roots = 0;
51 int trim_pool = 0;
52 int destroy_pool = 0;
set_flags(int n)53 void set_flags ( int n )
54 {
55 switch (n) {
56 case 0:
57 static_roots = 0;
58 trim_pool = 0;
59 destroy_pool = 0;
60 break;
61 case 1:
62 static_roots = 0;
63 trim_pool = 1;
64 destroy_pool = 0;
65 break;
66 case 2:
67 static_roots = 0;
68 trim_pool = 0;
69 destroy_pool = 1;
70 break;
71 case 3:
72 static_roots = 1;
73 trim_pool = 0;
74 destroy_pool = 0;
75 break;
76 case 4:
77 static_roots = 1;
78 trim_pool = 1;
79 destroy_pool = 0;
80 break;
81 case 5:
82 static_roots = 1;
83 trim_pool = 0;
84 destroy_pool = 1;
85 break;
86 default:
87 assert(0);
88 }
89 }
90
91
92 struct cell *cells_static[N];
93
94
main(int argc,char ** argv)95 int main( int argc, char** argv )
96 {
97 struct cell *cells_local[N];
98 int arg;
99 size_t i;
100 struct pool *p = allocate_pool();
101 struct cell **cells = static_roots ? cells_static : cells_local;
102
103 assert(argc == 2);
104 assert(argv[1]);
105 assert(strlen(argv[1]) == 1);
106 assert(argv[1][0] >= '0' && argv[1][0] <= '5');
107 arg = atoi( argv[1] );
108 set_flags( arg );
109
110 memset(cells_static, 0, sizeof(cells_static));
111 memset(cells_local, 0, sizeof(cells_local));
112
113 for (i = 0; i < N; ++i) {
114 cells[i] = allocate_from_pool(p, sizeof(struct cell));
115 }
116
117 if (trim_pool)
118 VALGRIND_MEMPOOL_TRIM(p,
119 p->buf+(10 * sizeof(struct cell)),
120 20 * sizeof(struct cell) + 2);
121
122 if (destroy_pool)
123 VALGRIND_DESTROY_MEMPOOL(p);
124
125 return 0;
126 }
127