0

I am currently trying to make a linked list and initialize it within a function. It looks like this:

void add_forest(node_t *head, unsigned char value)
{
    int key;
    node_t *current = head;
    while (current->next != NULL)
    {
        current = current->next;
    }

}

int main()
{
    node_t *head;
    *head = init_forest(); //error here
}

I am currently getting a segfault at the following area in my code and can not figure out why. I am creating the head in init_forest() and then passing back in the main. When I go through the init_forest() the tree does become built. Any suggestions?

6
  • 1
    Please add the definition of the structure type, and indent the code! Commented Feb 16, 2015 at 20:50
  • I'm suspicious that the line current->next = head = (node_t *)malloc(sizeof(node_t)); assigning to head in add_forest() is to blame. Commented Feb 16, 2015 at 20:52
  • Also learn to use the debugger. gdb is your friend! Commented Feb 16, 2015 at 20:52
  • I am using gdb but can not figure out why it is giving me the seg fault there. I also updated my code above. Commented Feb 16, 2015 at 20:54
  • return *head; seems a little sketchy, since you change head in current->next = head = (node_t *)malloc(sizeof(node_t));. I take that back, the second time you enter add_forest, in while(current->next != NULL) you are dereferencing a likely null object (since you changed the contents of head in the previous call to add_forest). Maybe? Commented Feb 16, 2015 at 20:55

1 Answer 1

3

The immediate problem is in main():

node_t *head;
*head = init_forest();

head is an uninitialized pointer; you can't dereference it, and you don't actually want to. You should be using:

node_t *head = init_forest();

But you then need to ensure that init_forest() returns a node_t *, rather than a node_t value. This is the more orthodox style for such linked list management functions. You allocated the structure in the function; if you return a copy of the structure rather than a pointer to the structure, you're leaking memory (and you end up with other problems later).

Sign up to request clarification or add additional context in comments.

2 Comments

I tried to do that and I get the following compile error: error: incompatible types when initializing type ‘struct node_t *’ using type ‘node_t’
See the update...you need to fix init_forest() to return a node_t *, with at least the consequential change that return *head; becomes return head;.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.