为什么此功能显示分段错误?

时间:2017-08-28 17:31:33

标签: c linked-list segmentation-fault

这是一个插入已排序链表的函数,但它显示了分段错误(SIGSEGV)

void sortedInsert(struct node **head_ref, int data) {
    struct node *new_node, *prev, *current;
    new_node = (struct node*)malloc(sizeof(struct node));
    new_node->data = data;
    new_node->next = NULL;
    if (*head_ref == NULL || (*head_ref)->data > data) {
        new_node->next = *head_ref;
        *head_ref = new_node;
        return;
    }
    current = *head_ref;
    prev = NULL;
    while (current->data < data && current != NULL) {
        prev = current;
        current = current->next;
    }
    prev->next = new_node;
    new_node->next = current;
}

3 个答案:

答案 0 :(得分:3)

这里的分段错误很可能是因为声明:

while(current->data<data&&current!=NULL)
    {
        prev=current;
        current=current->next;
    }

此处的当前指针被取消引用而未检查NULL。您应该尝试将条件更改为while(current && current->data<data),以便在取消引用之前检查指针是否为NULL。

答案 1 :(得分:1)

错误在于:while (current->data < data && current != NULL)。在取消引用之前,必须先针对NULL 检查指针:

while (current != NULL && current->data < data)

请注意,可以使用单个循环简化此功能:

void sortedInsert(struct node **head_ref, int data) {
    struct node *new_node;
    while (*head_ref && (*head_ref)->data <= data) {
        head_ref = &(*head_ref)->next;
    }
    new_node = malloc(sizeof(struct node));
    if (new_node == NULL) {
        /* handle the error */
        ...
    } else {
        new_node->data = data;
        new_node->next = *head_ref;
        *head_ref = new_node;
    }
}

答案 2 :(得分:0)

如果此语句在第一次迭代时失败:

while(current->data<data&&current!=NULL)

然后这句话:

prev->next=new_node;

将访问地址0的偏移量,这几乎总是会导致seg故障事件。