1libtalloc_destructors(3) talloc libtalloc_destructors(3)
2
3
4
6 libtalloc_destructors - Chapter 4: Using destructors
7
8
10 Destructors are well known methods in the world of object oriented
11 programming. A destructor is a method of an object that is
12 automatically run when the object is destroyed. It is usually used to
13 return resources taken by the object back to the system (e.g. closing
14 file descriptors, terminating connection to a database, deallocating
15 memory).
16
17 With talloc we can take the advantage of destructors even in C. We can
18 easily attach our own destructor to a talloc context. When the context
19 is freed, the destructor will run automatically.
20
21 To attach/detach a destructor to a talloc context use:
22 talloc_set_destructor().
23
25 Imagine that we have a dynamically created linked list. Before we
26 deallocate an element of the list, we need to make sure that we have
27 successfully removed it from the list. Normally, this would be done by
28 two commands in the exact order: remove it from the list and then free
29 the element. With talloc, we can do this at once by setting a
30 destructor on the element which will remove it from the list and
31 talloc_free() will do the rest.
32
33 The destructor would be:
34
35 int list_remove(void *ctx)
36 {
37 struct list_el *el = NULL;
38 el = talloc_get_type_abort(ctx, struct list_el);
39 /* remove element from the list */
40 }
41
42 GCC version 3 and newer can check for the types during the compilation.
43 So if it is our major compiler, we can use a more advanced destructor:
44
45 int list_remove(struct list_el *el)
46 {
47 /* remove element from the list */
48 }
49
50 Now we will assign the destructor to the list element. We can do this
51 directly in the function that inserts it.
52
53 struct list_el* list_insert(TALLOC_CTX *mem_ctx,
54 struct list_el *where,
55 void *ptr)
56 {
57 struct list_el *el = talloc(mem_ctx, struct list_el);
58 el->data = ptr;
59 /* insert into list */
60
61 talloc_set_destructor(el, list_remove);
62 return el;
63 }
64
65 Because talloc is a hierarchical memory allocator, we can go a step
66 further and free the data with the element as well:
67
68 struct list_el* list_insert_free(TALLOC_CTX *mem_ctx,
69 struct list_el *where,
70 void *ptr)
71 {
72 struct list_el *el = NULL;
73 el = list_insert(mem_ctx, where, ptr);
74
75 talloc_steal(el, ptr);
76
77 return el;
78 }
79
80Version 2.0 Thu Jul 21 2022 libtalloc_destructors(3)