6 * talloc_link - link helper for talloc
8 * Talloc references can be confusing and buggy. In the cases where an object
9 * needs multiple parents, all parents need to be aware of the situation; thus
10 * talloc_link is a helper where all "parents" talloc_link an object they
11 * agree to share ownership of.
14 * // Silly program which keeps a cache of uppercased strings.
15 * // The cache wants to keep strings around even after they may have
16 * // been "freed" by the caller.
21 * #include <ccan/talloc/talloc.h>
22 * #include <ccan/talloc_link/talloc_link.h>
29 * static struct upcache *cache;
30 * static unsigned int cache_hits = 0;
31 * #define CACHE_SIZE 4
32 * static void init_upcase(void)
34 * cache = talloc_zero_array(NULL, struct upcache, CACHE_SIZE);
37 * static struct upcache *lookup_upcase(const char *str)
40 * for (i = 0; i < CACHE_SIZE; i++)
41 * if (cache[i].str && !strcmp(cache[i].str, str)) {
48 * static struct upcache *new_upcase(const char *str)
53 * upstr = talloc_linked(cache, talloc_strdup(NULL, str));
57 * i = random() % CACHE_SIZE;
59 * // Throw out old: works fine if cache[i].upstr is NULL.
60 * talloc_delink(cache, cache[i].upstr);
62 * // Replace with new.
64 * cache[i].upstr = upstr;
66 * *upstr = toupper(*upstr);
72 * // If you want to keep the result, talloc_link it.
73 * static const char *get_upcase(const char *str)
75 * struct upcache *uc = lookup_upcase(str);
77 * uc = new_upcase(str);
83 * static void exit_upcase(void)
86 * printf("Cache hits: %u\n", cache_hits);
89 * int main(int argc, char *argv[])
92 * const char **values;
94 * // Will dump any memory leaks to stderr on exit.
95 * talloc_enable_leak_report();
97 * // Initialize cache.
100 * // Throw values in.
101 * values = talloc_array(NULL, const char *, argc);
102 * for (i = 1; i < argc; i++) {
103 * values[i-1] = talloc_link(values, get_upcase(argv[i]));
105 * err(1, "Out of memory");
107 * // This will free all the values, but cache will still work.
108 * talloc_free(values);
111 * values = talloc_array(NULL, const char *, argc);
112 * for (i = 1; i < argc; i++) {
113 * values[i-1] = talloc_link(values, get_upcase(argv[i]));
115 * err(1, "Out of memory");
118 * // This will remove cache links, but we still have a link.
121 * // Show values, so we output something.
122 * for (i = 0; i < argc - 1; i++)
123 * printf("%s ", values[i]);
126 * // This will finally free the upcase strings (last link).
127 * talloc_free(values);
132 * License: GPL (v2 or any later version)
133 * Author: Rusty Russell <rusty@rustcorp.com.au>
135 int main(int argc, char *argv[])
140 if (strcmp(argv[1], "depends") == 0) {
141 printf("ccan/talloc\n");
142 printf("ccan/list\n");