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

时间:2018-09-29 19:57:30

标签: c

遇到Segmentation错误,请在下面的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;
}

错误消息

2 个答案:

答案 0 :(得分:1)

问题是

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

设置保留空间后为新节点的值

*new = malloc ( sizeof (struct SinglyLinkedListNode)) ...

new->data = data;
new->next = NULL;

答案 1 :(得分:0)

修改为以下代码段,现在可以正常工作,还删除了额外的上一个指针跟踪。

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