C++:分割故障
我的C++代码C++:分割故障
#include <iostream>
#include <cstdlib>
using namespace std ;
struct Node {
int data ;
struct Node* next;
};
Node* Insert(Node *head,int data);
int main(){
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 7;
head->next = second;
second->data = 17;
second->next = third;
third->data = 37;
third->next = NULL;
head = Insert(head,3);
}
Node* Insert(Node *head,int data)
{
while (true)
{ cout << "hey" ;
if (head == NULL)
{
cout << "hey";
head->data = data ;
head->next = NULL ;
break ;
}
head = head->next ;
}
return head;
}
我特林学习链表在C++中。 我正在通过一个头和数据插入节点使用我已经定义的Insert()
函数。
我的输出端子
Segmentation fault (core dumped)
我觉得我在一个错误的方式invocating Insert()
功能。 请帮忙! 谢谢!
你错过了这head
是NULL
if语句,当它进入你。
这应该修复它:
Node* Insert(Node *head,int data) {
while (head != NULL) {
if (head->next == NULL) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data ;
newNode->next = NULL ;
head->next = newNode;
head = newNode;
break ;
}
head = head->next ;
}
return head;
}
请注意,当您尝试在空列表(即NULL)上插入值时,不会创建新列表,但在此情况下返回NULL。你应该检查这是否是所期望的行为 – LukeG
好点@LukeG,但是写入'Insert(NULL,4);'是没有意义的。因为你如何插入NULL? – sercanturkmen
有些事情错在这里:
if (head == NULL)
{
cout << "hey";
head->data = data ;
head->next = NULL ;
break ;
}
如果head
是NULL
,所以你不能分配data
其head->data
。这导致SIGSEGV。
问题就出在你的这部分代码:
if (head == NULL)
{
cout << "hey";
head->data = data ;
head->next = NULL ;
break ;
}
首先,你检查,如果头是空的,如果头部为NULL尝试取消引用(head->data
)头指针,这是不确定的行为,导致您的案例中出现段错误。
我提出以下算法:
if(head == NULL) {
Node* newHead = new Node();
newHead->data = data;
newHead->next = NULL;
return newHead;
}
while(head->next != NULL) head = head->next;
head->next = new Node();
head->next->data = data;
head->next->next = NULL;
return head;
调试它一步一个调试步骤,你就会知道什么错。 –
不要在C++代码中使用malloc。使用新的操作符。不要使用“using namespace std”并学会使用调试器而不是将print语句放在任何地方。 – LukeG
我试着在主函数下面的第一行添加'cout'。 它没有打印任何东西。 问题出在运行时iself –