【问题标题】:why this code to insert a node at the tail of a linked list caused segmentation error为什么此代码在链表的尾部插入节点导致分段错误
【发布时间】:2020-03-12 14:10:55
【问题描述】:

我正在尝试实现linkedlist函数以在列表末尾添加节点,但它几乎在每一行都会触发分段错误。

SinglyLinkedListNode* insertNodeAtTail(SinglyLinkedListNode* head, int Data) {

SinglyLinkedListNode* Node;
Node = malloc(sizeof(SinglyLinkedListNode));

SinglyLinkedListNode* current; 
current = head;


Node->data = Data;
Node->next = NULL;

if( head->next == NULL)     /* 0 element llist*/
{
    head = Node;
}
else
{
    //current = head;
    /*
            while(current->next != NULL) 
    */
    while(current->next != NULL)
    {
        current = current->next;
    }  // exit when current->next = lastNode->next = NULL
    current->next = Node;

}

【问题讨论】:

  • 提示:仔细考虑您的“0 元素列表”案例。特别是,分配给head 实际上并没有做任何事情……请记住,C 中的参数是按值传递的。
  • 您可以使用调试器或工具如 valgrind 或地址清理器来调试段错误。
  • 你能展示你的完整程序吗?我怀疑问题与调用此函数时列表的状态有关。
  • 请发布minimal reproducible example,其中包括包含哪些头文件、结构SinglyLinkedListNode 的定义以及其他关键的缺失细节,包括包含已发布代码片段的完整函数

标签: c data-structures linked-list clang


【解决方案1】:

这可能会导致段错误:

while(current->next != NULL)  /* if current is NULL 
dereferencing it will cause segfault. */

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-07
    • 2012-08-14
    • 1970-01-01
    • 2011-01-10
    • 2012-01-15
    • 2021-12-09
    • 2023-03-27
    相关资源
    最近更新 更多