banana
banana

Reputation: 369

Linked list segmentation fault in terminal, but not in debugger

I wrote a function that appends a value to the end of a linked list made up of val and next. However, I keep getting the error: Segmentation Fault 11: core dumped. When I run this on gdb, though, I do not get any errors. Any thoughts?

intlist* intlist_append(intlist* xs, int val) 
{
    intlist* new = (intlist*)malloc(sizeof(intlist*));
    new->val = val;
    new->next = NULL;
    intlist* ys = xs;
    while(ys->next) 
    {
        ys = ys->next;
    }
    ys->next = new;
    free(new);
    return xs;
}

Upvotes: 1

Views: 99

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311078

This part of the function

    // ...
    intlist* ys = xs;
    while(ys->next) 
    {
        ys = ys->next;
    }
    ys->next = new;
    free(new);
    return xs;
}

is wrong. First of all xs can be equal to NULL. In this case using the expression ys->next results in undefined behavior.

Secondly you shall not free the node new. Otherwise the function does not make sense.

Thirdly, the head stored in the local variable ys can be changed. However the value of xs will not be changed. In this case the function returns the unchanged value of the variable xs.

Also the first statement of the function is also wrong

intlist* new = (intlist*)malloc(sizeof(intlist*));
                                       ^^^^^^^^

There shall be

intlist* new = (intlist*)malloc(sizeof(intlist));
                                       ^^^^^^^

The function can be defined the following way

intlist * intlist_append( intlist *xs, int val ) 
{
    intlist *new_node = malloc( sizeof( intlist ) );

    if ( new_node != NULL )
    {
        new_node->val  = val;
        new_node->next = NULL;

        intlist **current = &xs;

        while ( *current ) current = &( *current )->next; 

        *current = new_node;
    }

    return xs;
}

Upvotes: 1

Related Questions