制作链表:获取分段错误

Making a linked list: getting segmentation faults

本文关键字:分段 错误 获取 链表      更新时间:2023-10-16

我正在练习如何在 c++ 中制作链表,代码发布在下面。我分配了错误的内存吗?我不确定是我的节点构造函数还是列表导致错误,但我不断收到分段错误。我是一个初学者,我真的很想很好地理解内存分配。

主.cpp:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include "list.h"
using namespace std;

int main(void)
{
int option;
list *linked;
linked = new list;


while(1)
{
// menu
cout<<"********************************************"<<endl;
cout<<" what option would you like to use "<<endl;
cout<<" 1.add a node"<<endl;
cout<<" 2.show list"<<endl;
cout<<" 3.delete node"<<endl;
cout<<"********************************************"<<endl;
cin>>option;
//switch for option 
    switch(option)
    {
     case 1 : 
     cout<<"you picked add a node"<<endl;
     (*linked).add_node();
     break;
     case 2 :
     cout<<"you picked show list"<<endl;
     break;
     case 3 :
     cout<<"you picked delete node"<<endl;
     break;
     default:
     cout<<"thats not a valid option"<<endl;
     break;
    }
}
return 0;
}

列表.h:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
using namespace std;
class node
{
private:
node *next;
node *prev;
string note;
public:
// constructor
node();
//gets
node* get_next(void)
{return next;}
node* get_prev(void)
{return prev;}
// setts
void set_next(node* x)
{next=x;}
void set_prev(node* x)
{prev=x;}
};
class list
{   
private:
node *head, *current, *tail;

public:
//constructor
list();
void add_node(void);
};
 node::node(void)
 {
string x;
cout<<"hi"<<endl;
//set front and back null
next=NULL;
prev=NULL;
//write the note
cout<<" what note would you like to write in the node"<<endl;
cin>>x;
note=x;
}
list::list(void){
//start the list pointing to null
head = tail = NULL;
}
void list::add_node(void)
{

//make first node
    if(head=0){
 head = new node;
 cout<<"1"<<endl;
 }
//make 2nd node
else if((*head).get_next()==0){
 cout<<"2"<<endl;
 node* temp;// buffer
 temp= new node;
 (*head).set_next(temp);
 (*head).set_prev(temp);
 (*tail).set_next(head);
 (*tail).set_prev(head);
 }


 }

我认为您在添加节点时遇到了错误。

我看到的问题是,在第一次插入后,您已经正确分配了一个头部,但对尾部没有做任何事情。在下一次插入中,由于您的头部有效,您进入"创建第二个节点"代码块,在这里您尝试取消引用尚未初始化的尾部成员。