C++中链表实现中的分段错误
Segmentation fault in linked list implementation in C++
我正在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;
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?