0

I am trying to initialize a tree by doing this:

typedef struct {
    char *value;
    struct children_list *children;
} tree;

typedef struct t_children_list {
    tree *child;
    struct t_children_list *next;
} children_list;

void initializeTree(tree *root, char *input)
{
  if((root = malloc(sizeof(tree))) == NULL) { abort(); }
  root->value = input;
}

void main()
{
  // Create the tree
  char *input = "aaaaaa";
  tree *my_tree = NULL;

  initializeTree(my_tree, input);
}

But I am getting a segmentation fault. Why is that happening? I am passing a pointer to a function and I am reserving memory inside of it. Is that wrong?

Hommer Smith
  • 26,772
  • 56
  • 167
  • 296

1 Answers1

2

the pointer 'my_tree' is passed by value (as is the only way it is done in C)

so my_tree is basically COPIED and no assignment of 'root' has any effect on the 'my_tree' variable.

you want to get a pointer back so pass a pointer to a pointer (**) and then init *root to actually modify my tree

void initializeTree(tree **pRoot, char *input)
{
  if((*pRoot = malloc(sizeof(tree))) == NULL) { abort(); }
  *pRroot->value = input;
}

void main()
{
  // Create the tree
  char *input = "aaaaaa";
  tree *my_tree = NULL;

  initializeTree(&my_tree, input);
}

OR don't pass it at all but return it:

tree *initializeTree(char *input)
{
  tree *root = NULL;
  if((root = malloc(sizeof(tree))) == NULL) { abort(); }
  root->value = input;
  return root;
}

void main()
{
  // Create the tree
  char *input = "aaaaaa";
  tree *my_tree = initializeTree(input);
}
Daij-Djan
  • 49,552
  • 17
  • 113
  • 135