链表中的字母排序,c中的seg错误

时间:2016-06-11 01:25:41

标签: c sorting

我尝试按字母顺序对链接列表进行排序,我正在使用我的排序功能seg fault。如何按字母顺序对列表进行排序。

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

2 个答案:

答案 0 :(得分:1)

在第

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

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

需要保护。可能的解决方案:

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

答案 1 :(得分:0)

仅仅因为list不是空,并不意味着list->next也不是空的;确保它不是在使用之前。