talloc_tos() in common code

Jeremy Allison jra at samba.org
Wed Apr 13 13:23:02 MDT 2011

On Wed, Apr 13, 2011 at 09:00:31PM +0400, Matthieu Patou wrote:
> Hello Volker and Jeremy,
> >I think this is a good idea. talloc_tos() is such a
> >useful concept that working without it tends to make
> >code a lot more clumsy.
> Could you introduce the benefits of talloc_tos ?

talloc_tos() allows an implicit talloc context to
be available deep within nested functions without
having to explicitly pass it as a parameter.

For most of the smbd code, we receive a request
from the client, and then allocate a lot of temporary
memory whilst processing that request.

The use is to allocate a talloc stackframe associated
with the incoming requests, then use talloc_tos() to
get an implicit context anywhere needed whilst allocating
temporary memory processing the request.

If long-term storage is needed, then allocated memory
must be talloc_move()'d to a longer term context.

But for most normal uses it's wonderful, as it is
a self-cleaning talloc context meaning code flow
looks more natural avoiding many:

if (err) goto out;

code paths to free memory in error paths. It's
a good protection against memory leaks too.

For example:

frame = talloc_stackframe();



As an advantage, if the top level frame is allocated
with talloc_pool(), and the tallocs off talloc_tos()
below are small enough to fit within the pool, we only
do *one* malloc()/free() pair for the whole processing

> And why is it forbidden in source4 (maybe a question for the andrews).

The top level stack has to be set up usually
in program main(). Actually it will work without
initial setup, but means a memory leak at the top


More information about the samba-technical mailing list