-2

I am trying to print my linked list until the next node is NULL but I am seg faulting after printing two nodes. mov is my linked list nodes.

while(mov->next != NULL)
{
    printf("%s\n", mov->movie_title);
    printf("%s\n", mov->...etc...)

    free(mov);
    mov = mov->next;
}

This is my push function that I use to assign the data to the nodes.

void push(movie** mov)
{
    movie* new = malloc(sizeof(movie));
    new->next = (*mov);
    (*mov) = new;
}

After assigning the data to the node, I call push(&mov);

I was using an array of structs before but since the amount of memory needed to store became very large, I thought it wouldn't work very well since malloc allocates a contiguous block of memory where as with nodes, I can allocate small chunks of memory for each node.

3
  • Question: How do you ensure mov->next is NULL for the last node? Commented Nov 28, 2017 at 7:27
  • 6
    Ouch! free(mov); and afterwards mov = mov->next;. You may not access data which has been free-d. Commented Nov 28, 2017 at 7:28
  • You should read this: minimal reproducible example Commented Nov 28, 2017 at 7:40

1 Answer 1

1

The problem here is in the free(mov) line and what comes after.

You're freein' mov then trying to assign mov->next to it, you see where the problem is, no ?
mov->next can't be accessed anymore since you free'd the struct which was storing it

A better way to print an entire linked list is to set a "temporary" variable which will browse each node of the list and print every values while doing it.

Here's an example :

void printMovieList(movie** mov) {
    movie* temp = *mov;

    while(temp != NULL)
    {
        printf("%s\n", temp->movie_title);
        printf("%s\n", temp->...etc...);
        temp = temp->next;
    }
}
1
  • 1
    Damn I feel dumb, that was so obvious. Thanks.
    – codemonkey
    Commented Nov 28, 2017 at 18:49

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.