forked from a-p-jo/allocator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsample.c
More file actions
51 lines (42 loc) · 1.25 KB
/
sample.c
File metadata and controls
51 lines (42 loc) · 1.25 KB
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
#include "allocator.h"
/* An allocator that uses statically allocated memory */
static allocator sta;
#define sta_alloc(sz) allocator_alloc(&sta, (sz))
#define sta_free(p) allocator_free(&sta, (p))
#define sta_for_blocks(f) allocator_for_blocks(&sta, (f))
static void sta_init(void)
{
static max_align_t heap[4096/sizeof(max_align_t)];
sta = ALLOCATOR_INIT;
allocator_add(&sta, heap, sizeof(heap));
}
#include <string.h> /* strlen(), memcpy() */
#include <stdio.h> /* puts(), fputs(), stderr */
#include <assert.h> /* assert() */
static void pblksz(size_t blksz) {printf("%zu ", blksz);}
static void pstatus(const char *msg)
{
fputs(msg, stdout);
sta_for_blocks(pblksz);
putchar('\n');
}
int main(int argc, char **argv)
{
sta_init();
pstatus("Initial blocksize(s) : ");
/* Allocate and deepcopy argv */
char **args = sta_alloc(argc * sizeof(char *));
assert(args);
for (int i = 0; i < argc; i++) {
size_t len = strlen(argv[i]);
assert( (args[i] = sta_alloc(len)) );
memcpy(args[i], argv[i], len);
}
pstatus("Blocksize(s) after allocations : ");
/* Print the allocated copy backwards and free it */
while (argc --> 0)
puts(args[argc]), sta_free(args[argc]);
sta_free(args);
pstatus("Blocksize(s) after freeing : ");
return 0;
}