制作链表:获取分段错误
Making a linked list: getting segmentation faults
我正在练习如何在 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);
}
}
我认为您在添加节点时遇到了错误。
我看到的问题是,在第一次插入后,您已经正确分配了一个头部,但对尾部没有做任何事情。在下一次插入中,由于您的头部有效,您进入"创建第二个节点"代码块,在这里您尝试取消引用尚未初始化的尾部成员。
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?