我正在学习如何在C中构建链表。我的程序编译了,但由于某种原因我无法理解,我遇到了分段错误。我想弄清楚这个问题已经有一段时间了,但运气不好。这是故障代码:
int len()
{
struct list * current = head;
int length = 0;
while (current != NULL)
{
length++;
current = current -> next; //move to next node
}
return length;
}
struct list * search ( int key)
{
struct list * current = head;
while (current != NULL && current->data != key)
current = current -> next;
if (current != NULL && current -> data == key)
return current;
return NULL;
}
/* Insert a new data element with key d into the end of the list. */
void insert(int d ) // at the end
{
struct list * current = head;
struct list * new;
while (current -> next != NULL)
current = current -> next;
new = (struct list *)malloc(sizeof(struct list));
new -> data = d;
current -> next = new;
new -> next = NULL;
}
void insertAfter(int d, int where ) // insert at the middle
{
struct list * marker = head;
struct list * new;
while(marker -> data != where)
marker = marker -> next;
new = (struct list*)malloc(sizeof(struct list));
new -> next = marker -> next;
marker -> next = new;
new -> data = d;
}
/* Remove the node with value d from the list */
/* assume no duplicated keys in the list */
/* If the list is empty, call prtError() to display an error message and return -1. */
void delete(int d)
{
struct list * current1 = head;
struct list * current2;
if (len() == 0)
{ //prtError("empty");
exit(0);
}
if (head -> data == d)
{
head = head -> next;
}
//Check if last node contains element
while (current1->next->next != NULL)
current1 = current1->next;
if(current1->next->data == d)
current1->next == NULL;
current1 = head; //move current1 back to front */
while(current1 -> next -> data != d)
current1 = current1 -> next;
current2 = current1 -> next;
current1 -> next = current2 -> next;
}
我在以下行的删除方法中遇到分段错误:
while(current1 -> next -> data != d)
为什么这是错误的?
在insert
:中,您有几个问题
while (current -> next != NULL)
您没有检查current
是否为NULL
。delete
:中也存在类似问题
if (head -> data == d)
你需要在这里检查head
和:
while (current1->next->next != NULL)
也是一个问题。
插入后出现错误,因为您将溢出未找到元素的列表末尾。
您发布的代码有很多问题,但您在评论中提到了insert()
。它崩溃的原因是,如果调用insert()
时head
为NULL,则将取消引用NULL指针。
当head
为NULL时,您将需要一个特殊的案例来插入:
if (head) {
while (current -> next != NULL)
current = current -> next;
}
new = (struct list *)malloc(sizeof(struct list));
new -> data = d;
if (current) {
current -> next = new;
} else {
head = new;
}
new -> next = NULL;
您应该在其他功能中检查类似的问题。使用search()
函数作为避免在循环中取消引用NULL指针的示例。
在insert
中,
while(current->next != NULL) current = current->next;
这将保证current == NULL
。
current->next = new;
每次都会崩溃。
可能在insertAfter
:中
while(marker -> data != where)
marker = marker -> next;
如果没有找到具有data == where
的节点,则marker
将是NULL
指针NULL
指针稍后在您的代码中被取消引用:
new = marker -> next;
这是一个错误。检查marker->next != NULL
是否应避免:
while(marker->next != NULL && marker -> data != where)
marker = marker -> next;
但您应该尝试使用调试符号(-g
选项)编译程序,并在类似GDB的调试器中逐行运行。