Search code examples
clistfault

Segmentation fault when trying to print linked list C


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.


Solution

  • 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;
        }
    }