C++中链表实现中的分段错误

Segmentation fault in linked list implementation in C++

本文关键字:分段 错误 实现 链表 C++      更新时间:2023-10-16

我正在C++中编写一个函数,将类型为"int"的"data"添加到链表的末尾。

void insert_back()
{
 int no;
 node *temp;
 cout<<"nEnter the number"<<"n";
 cin>>no;
 temp = head;
 if(temp != NULL)
 {
         while(temp != NULL)
                    temp = temp->next;
 }
 temp->next = (node*)malloc(sizeof(node));
 temp = temp->next;
 temp->data = no;
 temp->next = NULL;

}

然而,在temp->next=(node*)malloc(sizeof(node))这一行,我得到了一个访问冲突错误(分段错误)。我没有发现任何根本错误。你能告诉我这个问题吗?

如果您想获得列表的最后一个节点,只需检查下一个成员是否为null,因为最后一个结点的上一个成员为null。

在您的代码中,您检查temp是否为null,而不是emp->next

while(temp != NULL)
    temp = temp->next;

将在循环结束时使temp为null。

此外,您还应该考虑头为空的条件。

void insert_back()
{
    int no;
    node *temp;
    cout<<"nEnter the number"<<"n";
    cin>>no;
    temp = head;
    if(temp != NULL)
    {
        while(temp->next != NULL)
            temp = temp->next;
        temp->next = (node*)malloc(sizeof(node));
        temp = temp->next;
        temp->data = no;
        temp->next = NULL;
    }else{
        head = (node*)malloc(sizeof(node));
        head->data = no;
        head->next = NULL;
    }
}

就在执行该行之前,temp将为null。然后取消引用它。

您所引用的temp不存在,temp为NULL。要更正此问题,请不要使用temp=while循环条件为NULL,请使用temp->next!=NULL。

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

如果有人有这个问题,只需检查您是否为List类创建了默认构造函数。在该默认构造函数中;使你的头=NULL";;

代码:

class List
{
public:
Node *head;
List()
 {
    head = NULL;
 }
}

试试这个:-while(temp->next!=NULL)而不是while(temp!=NULL)

这是一个如此愚蠢的错误,我面对它,告诉我花了几个月的时间才看到如此愚蠢的失误。

while(temp != NULL)
    temp = temp->next;

上面的代码会将您带到列表中的最后一个节点。因此,假设将节点添加到temp本身,而不是temp->next

temp = (node*)malloc(sizeof(node));

现在最后一个节点的子节点应该为NULL。

temp->next = NULL;