1libtalloc_stealing(3)               talloc               libtalloc_stealing(3)
2
3
4

NAME

6       libtalloc_stealing - Chapter 2: Stealing a context
7
8

Stealing a context

10       Talloc has the ability to change the parent of a talloc context to
11       another one. This operation is commonly referred to as stealing and it
12       is one of the most important actions performed with talloc contexts.
13
14       Stealing a context is necessary if we want the pointer to outlive the
15       context it is created on. This has many possible use cases, for
16       instance stealing a result of a database search to an in-memory cache
17       context, changing the parent of a field of a generic structure to a
18       more specific one or vice-versa. The most common scenario, at least in
19       Samba, is to steal output data from a function-specific context to the
20       output context given as an argument of that function.
21
22       struct foo {
23           char *a1;
24           char *a2;
25           char *a3;
26       };
27
28       struct bar {
29           char *wurst;
30           struct foo *foo;
31       };
32
33       struct foo *foo = talloc_zero(ctx, struct foo);
34       foo->a1 = talloc_strdup(foo, "a1");
35       foo->a2 = talloc_strdup(foo, "a2");
36       foo->a3 = talloc_strdup(foo, "a3");
37
38       struct bar *bar = talloc_zero(NULL, struct bar);
39       /* change parent of foo from ctx to bar */
40       bar->foo = talloc_steal(bar, foo);
41
42       /* or do the same but assign foo = NULL */
43       bar->foo = talloc_move(bar, &foo);
44
45       The talloc_move() function is similar to the talloc_steal() function
46       but additionally sets the source pointer to NULL.
47
48       In general, the source pointer itself is not changed (it only replaces
49       the parent in the meta data). But the common usage is that the result
50       is assigned to another variable, thus further accessing the pointer
51       from the original variable should be avoided unless it is necessary. In
52       this case talloc_move() is the preferred way of stealing a context.
53       Additionally sets the source pointer to NULL, thus.protects the pointer
54       from being accidentally freed and accessed using the old variable after
55       its parent has been changed.
56
57Version 2.0                     Thu Jul 21 2022          libtalloc_stealing(3)
Impressum