为什么我的编译器在执行此代码时出现分段错误?


#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
struct Node {
int data;
Node* next;
};
struct Node* takeInput(){
struct Node* head;
cout<<"Enter element:";
int data;
cin>>data;
while(data!=-1){
struct Node* newNode=new (struct Node);
newNode->data=data;
newNode->next=NULL;
if(head==NULL){
head=newNode;
}
else{
struct Node* temp=new (struct Node);
while(temp->next!=NULL){
temp=temp->next;
}
temp->next=newNode;
}
cout<<"Enter next element: ";
cin>>data;
}
return head;
}
void print(struct Node* head){

while(head->next!=NULL){
cout<<head->data<<"->";
head=head->next;
}
}
int main(){
struct Node* head = new (struct Node);
head = takeInput();
print(head);
}

执行 print() 函数时发生分段错误。 无需执行打印函数,代码即可完美运行。代码从用户那里获取输入,但在我尝试打印链表时崩溃。 我正在Linux操作系统上使用带有代码块IDE的gcc编译器。

您的代码充满了对未初始化变量的访问、取消引用未初始化的成员以及产生内存泄漏

if(head==NULL),其中head是一个没有初始化器的局部变量

while(temp->next!=NULL),其中刚刚创建了temp并且从未分配next

while(head->next!=NULL),其中head是一个函数参数,可能是NULL

struct Node* head = new (struct Node); head = takeInput()泄漏。

struct Node* temp=new (struct Node); ... temp=temp->next泄漏。

在不更改太多代码的情况下,以下内容应该可以工作:

struct Node* takeInput(struct Node* head) { 
cout<<"Enter element:";
int data;
cin>>data;
while(data!=-1){
struct Node* newNode=new (struct Node);
newNode->data=data;
newNode->next=NULL;
if(head==NULL){
head=newNode;
}
else{
struct Node* temp=head;  // start at the head
while(temp->next!=NULL){
temp=temp->next;
}
temp->next=newNode;
}
cout<<"Enter next element: ";
cin>>data;
}
return head;
}
void print(struct Node* head){

while(head!=NULL){  // test head, not it's successor
cout<<head->data<<"->";
head=head->next;
}
}
int main(){
struct Node* head = takeInput(NULL);
print(head);
}

当您检查时struct Node* head;是未初始化的if(head==NULL)它几乎可以肯定计算为 false。你在 else 中唯一要做的就是泄漏内存,然后返回一个未初始化的指针。当您尝试使用它时,它应该出现段错误。

struct Node* head;更改为struct Node* head=NULL;,将struct Node* temp=new (struct Node);更改为struct Node* temp=head;

主要更改struct Node* head = new (struct Node);struct Node* head = takeInput();并记住释放内存

最新更新