为什么我的编译器在执行此代码时会给我一个分段错误?

时间:2017-07-04 18:15:02

标签: c++ linked-list segmentation-fault

#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 OS上使用带有Code Blocks IDE的gcc编译器。

2 个答案:

答案 0 :(得分:1)

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

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);
}

答案 1 :(得分:0)

检查struct Node* head;时,

if(head==NULL)未初始化,几乎肯定会评估为false。你在else中唯一做的就是泄漏内存然后你返回一个未初始化的指针。当你尝试使用它时,只应该使用segfault。

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();并记得解除内存