6 * alloc - memory allocator routines
8 * The alloc module implements a simple allocator which you can use to
9 * dynamically allocate space within a region of memory. This can be useful
10 * for suballocations within a given region, or a memory-mapped file.
12 * All metadata is kept within the memory handed to the allocator: you only
13 * need hand the pointer and the size of the memory to each call.
15 * The region contents is always in offsets, so it can be mapped in different
16 * places, but is not endian-safe.
19 * #include <sys/mman.h>
21 * #include <sys/types.h>
23 * #include <sys/stat.h>
26 * #include <ccan/alloc/alloc.h>
28 * static void usage(const char *name)
30 * errx(1, "Usage: %s --create <mapfile>\n"
31 * " %s --check <mapfile>\n"
32 * " %s --alloc <mapfile>\n"
33 * " %s --free=<offset> <mapfile>\n", name, name, name, name);
36 * // Create a memory mapped file, and allocate from within it
37 * int main(int argc, char *argv[])
41 * enum { CREATE, CHECK, ALLOC, FREE } cmd;
46 * if (strcmp(argv[1], "--create") == 0)
48 * else if (strcmp(argv[1], "--check") == 0)
50 * else if (strcmp(argv[1], "--alloc") == 0)
52 * else if (strncmp(argv[1], "--free=", strlen("--free=")) == 0)
57 * if (cmd == CREATE) {
58 * fd = open(argv[2], O_RDWR|O_CREAT|O_EXCL, 0600);
60 * err(1, "Could not create %s", argv[2]);
61 * if (ftruncate(fd, 1048576) != 0)
62 * err(1, "Could not set length on %s", argv[2]);
64 * fd = open(argv[2], O_RDWR);
66 * err(1, "Could not open %s", argv[2]);
69 * a = mmap(NULL, 1048576, PROT_READ|PROT_WRITE, MAP_SHARED, fd,0);
70 * if (a == MAP_FAILED)
71 * err(1, "Could not map %s", argv[2]);
75 * alloc_init(a, 1048576);
78 * if (!alloc_check(a, 1048576))
79 * err(1, "Region is corrupt");
82 * p = alloc_get(a, 1048576, 1024, 16);
84 * errx(1, "Could not allocate");
85 * printf("%zu\n", (char *)p - (char *)a);
88 * p = (char *)a + atol(argv[1] + strlen("--free="));
89 * alloc_free(a, 1048576, p);
95 * License: LGPL (2 or any later version)
96 * Author: Rusty Russell <rusty@rustcorp.com.au>
98 int main(int argc, char *argv[])
103 if (strcmp(argv[1], "depends") == 0) {
104 printf("ccan/alignof\n");
105 printf("ccan/build_assert\n");
106 printf("ccan/compiler\n");
107 printf("ccan/ilog\n");
108 printf("ccan/likely\n");
109 printf("ccan/short_types\n");