在链表SEGV错误的末尾插入新节点



得到分割错误,请在下面的c代码逻辑中帮助解决问题。 程序因信号 SIGSEGV 终止,分段错误。

/*
* For your reference:
*
* SinglyLinkedListNode {
*     int data;
*     SinglyLinkedListNode* next;
* };
*
*/
SinglyLinkedListNode* insertNodeAtTail(SinglyLinkedListNode* head, int data) {
SinglyLinkedListNode *cur = head, 
*new = malloc ( sizeof (struct SinglyLinkedListNode)), *prev;

if ( head == NULL)
{
head = new;
return head;
}

while ( cur != NULL)
{
prev = cur;
cur = cur -> next;
}

prev -> next = new;
return head;
}

错误信息

问题是

cur = cur -> next; // You read an uninitialized value (garbage)

在预留空间后设置新节点的值

*new = malloc ( sizeof (struct SinglyLinkedListNode)) ...
new->data = data;
new->next = NULL;

修改为下面的代码片段,它现在可以工作了,还删除了额外的 prev 指针跟踪。

SinglyLinkedListNode* insertNodeAtTail(SinglyLinkedListNode* head, int data) {
SinglyLinkedListNode *cur = head, 
*new = malloc ( sizeof (struct SinglyLinkedListNode));
// assigning the data in new node
new -> data = data;
new -> next = NULL;

// check for NULL head
if ( head == NULL)
{
head = new;
return head;
}

// traverse till the end of the linked list
while ( cur -> next != NULL)
cur = cur -> next;

// attach new node at the end of the linked list
cur -> next = new;
return head;
}

最新更新