Junius L
Junius L

Reputation: 16142

Linked list alphabetical sort, seg fault in c

I'm trying to sort a linked list in alphabetical order, I'm getting seg fault with my sorting function. How can I sort my list alphabetically.

typedef struct  s_file
{
    char        *file_name;
    struct      s_file *next;
}               t_file;

void    sort_alpha(t_file **begin_list)
{
    t_file  *list;
    char    *tmp;

    list = *begin_list;
    if (list)
    {
        while (list)
        {
            if (strcmp(list->file_name, list->next->file_name) < 0)
            {
                tmp = list->file_name;
                list->file_name = list->next->file_name;
                list->next->file_name = tmp;
            }
            list = list->next;
        }
    }
}

Upvotes: 0

Views: 60

Answers (2)

sg7
sg7

Reputation: 6298

In the line

      if (strcmp(list->file_name, list->next->file_name) < 0)

      // list->next could be NULL so
      // list->next->file_name could give seg fault

A protection is needed. Possible solution:

void sort_alpha(t_file **begin_list)
{
t_file  *list;
char    *tmp;

list = *begin_list;
if (list)
{
    while (list && list->next)
    {

        if (strcmp(list->file_name, list->next->file_name) < 0)
        {
            tmp = list->file_name;
            list->file_name = list->next->file_name;
            list->next->file_name = tmp;
        }
        list = list->next;
    }
}
}

Upvotes: 1

Scott Hunter
Scott Hunter

Reputation: 49893

Just because list isn't null doesn't mean that list->next is also not null; make sure it is not before using it.

Upvotes: 0

Related Questions