talloc_reference bug?

Michael Cohen michael.cohen at netspeed.com.au
Mon Apr 30 15:07:26 GMT 2007

Hi there,
  The following example shows talloc_reference behaviour which perhaps needs to
  be better documented?

#include <stdlib.h>
#include <sys/types.h>
#include <stdarg.h>
#include <stdio.h>

#include "talloc.h"

// This is supposed to represent some other context which might be
// owned by something else
char *g_context;

// This string is supposed to hold a reference to a talloc string
char *some_string;

// This bit of code tries to take ownership of the string by adding a reference to it.
void process_string(char * string) {
  // We want to keep hold of the string - so we take a reference on it:
  talloc_reference(g_context, string);

  some_string = string;

// This function tries to use the reference taken above. When done it tries to free it.
void do_something() {
  // We expect some_string to be set and valid here (because we took a
  // reference to it before).

  printf("string is %s\n", some_string);

  // Ok we are dont with it now...

int main() {
  char *root;
  char *string;

  g_context = talloc_named_const(NULL, 1, "foreign context");

  // This is a provider of a string - the string is provided to the consumer
  // which does what they like with it.
  root = talloc_named_const(NULL, 1, "root context");

  // We just create a string:
  string = talloc_strdup(root, "hi there");

  // Now we simulate a processing of the string:

  // Now we free the string:

  // This function is finished:

  // Now we call some other bit of code:

  return 0;

The main issue is that the caller prepares a talloc context and provides it to
a client, and then frees the context after use. The client wants to retain a
reference to it, but in fact when the provider calls talloc_free(string) this
reference is being removed _instead_ of string being freed. When the other part
of the code wants to use its referenced string (and tries to free it when done)
this program will abort because that reference is no longer valid.

The solution is for the provider to use talloc_unlink() instead of talloc free
to ensure that the reference is maintained - but that kind of instroduces lots
of coupling between providers and consumers. i.e. the provider needs to know
that references will be used in the consumer to use talloc_unlink.


More information about the samba-technical mailing list