简体   繁体   English

为什么我的代码会出现分段错误?

[英]Why am I getting segmentation fault on my code?

I am trying to add an item to the linked list by traversing the list to create the next node.我试图通过遍历列表来创建下一个节点来向链表添加一个项目。 and the last node in the list to point to the newly created node.和列表中的最后一个节点指向新创建的节点。 But I am getting a core dump segmentation fault on it.但是我遇到了核心转储分段错误。

void linked_list_add(list_node_t *head, void *item)
{
    list_node_t *temp = head;

    while(temp->next != NULL)
    {
        temp = temp->next;
    }
    list_node_t *new_node = (list_node_t *)malloc(sizeof(list_node_t));

    new_node->data = item;
    new_node->next = NULL;
    new_node->prev = temp;

    //if(temp != NULL)
       // temp->next = new_node;
       // new_node->prev = temp;

}

TEST_F(LinkedList, Add)
{
    int i = 3;
    linked_list_add(list, &i);

    ASSERT_EQ(list->next->data, &i);

    i = 4;
    linked_list_add(list, &i);

    ASSERT_EQ(list->prev->data, &i);

    i = 5;
    linked_list_add(list, &i);

    ASSERT_EQ(list->next->data, &i);
}

This is an answer to summarize the comments.这是总结评论的答案。

There are likely at least 3 issues with the code as written:编写的代码可能至少有 3 个问题:

  1. When the code void linked_list_add(list_node_t *head, void *item) is passed arguments, you generally want to be able to handle a NULL pointer for head .当代码void linked_list_add(list_node_t *head, void *item)被传递参数时,您通常希望能够处理headNULL指针。 It looks like the while loop immediately goes into searching for the end of the list even if the head is null.看起来 while 循环会立即开始搜索列表的末尾,即使head为空也是如此。

  2. The newly added node, new_node gets the prev pointer updated so that the backwards searchs will be and shouldn't segfault.新添加的节点new_node更新了prev指针,以便向后搜索将是也不应该是段错误。 However, the forward searching isn't preserved.但是,不保留前向搜索。 By this I mean that the last non- NULL node in the linked list doesn't have the next pointer pointing to the new_node .我的意思是链表中的最后一个非NULL节点没有指向new_nodenext指针。

  3. The test ASSERT_EQ(list->prev->data, &i);测试ASSERT_EQ(list->prev->data, &i); is likely accessing either a random memory location or a NULL pointer.可能访问随机内存位置或NULL指针。 Given that the OP didn't post the declaration of the list struct it is difficult to say what the default values are/will be.鉴于 OP 没有发布list结构的声明,很难说默认值是/将是什么。 However, unless this list is circular, the value of list->prev is an uninitialized pointer.然而,除非这个列表是循环的,否则list->prev的值是一个未初始化的指针。 Depending on your setup (eg if there is setup code for the linked list that sets the pointers to null, you could be accessing a NULL pointer there too.根据您的设置(例如,如果链表的设置代码将指针设置为空,您也可以在那里访问NULL指针。

I hope this helps the OP solve their coding problem(s).我希望这有助于 OP 解决他们的编码问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM