talloc_incr_ref_count does not work

Michael Cohen michael.cohen at netspeed.com.au
Fri Dec 8 04:05:43 GMT 2006


Hi List,
 This may be a bug in documentation or my understanding of talloc but the
 talloc_incr_ref_count function does not work as expected. I am writing a
 python binding to a C module using talloc. This is good because its possible
 to tell python than when the opaque python object is garbage collected, it
 should call talloc_free on the talloc memory automatically. This approach
 generally works very well.

 I have a tree structure in memory, and can return to python a reference to any
 node. Because each node is created with the talloc context of its parent i
 need to increase the reference to the node when returning that node.
 Otherwise, if someone frees the root of the tree all nodes will be freed.

 I assumed that the correct function to use is talloc_incr_ref_count on the
 node before returning to python. Unfortunately when python frees the root of
 the tree, it fress everything else as well, despite the fact that the node has
 a reference code of 1. I assumed by reading the manual that it should free up
 to the node and stop there, decrementing the reference count of the node.

 It turns out that what happens in reality is that talloc_free cascades through
 the tree until it gets to the node in question. It then realises that the
 reference count is not zero, but that the other reference is to the null
 pointer. It then reparents the node to the node's parent and returns. However,
 the nodes parent continues with its talloc_free, and then frees the node
 anyway (because its now attached to it, and its reference count is zero).

 Here is a diagrem to explain:

 A -> B -> C

 A is parent of B which is parent of C. I call talloc_incr_ref_count on C which
 adds a reference to the null pointer to C. Then I call talloc free on A. This
 cascades to B which realises that the ref count is not zero with C. It then
 decreases the ref count, and becuase the other reference is to the null
 pointer - C is considered an orphan. It then reparents C back to A and
 returns. A then continues with its talloc_free cascade, but this time C is a
 child of A, and it gets freed because it has a ref count of 0.

 So the overall effect is that talloc_incr_ref_count does not work. the node
 gets freed anyway.

 Is this a bug? Why does talloc_free feel the need to reparent an orphan
 pointer? surely increasing ref count on an object without reason is a bug. My
 current work around is to allocate a talloc context and add a reference to a
 real context to C. This prevents C from being reparented.

Thanks,
 Michael.


More information about the samba-technical mailing list