这是一个插入到排序链表中的函数,但它显示分割错误(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;
}
这里的分段错误很可能是因为以下语句:
while(current->data<data&¤t!=NULL)
{
prev=current;
current=current->next;
}
此处的当前指针正在取消引用,而未检查 NULL。您应该尝试将条件更改为while(current && current->data<data)
,以便在取消引用之前检查指针是否为 NULL。
错误在这里: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;
}
}
如果此语句在第一次迭代时失败:
while(current->data<data&¤t!=NULL)
那么这句话:
prev->next=new_node;
将访问地址 0 的偏移量,这几乎总是会导致 SEG 故障事件。