2016-05-24 4 views
-3

セグメンテーションフォールト取得を。私は間違ってメモリを割り当てていますか?私はそれがエラーを引き起こすノードまたはリストのための私のコンストラクタかどうか分からないが、私はセグメンテーションフォールトを取得し続けている。私は初心者です。私は実際にメモリ割り当てをよく理解しようとしています。リンクリストを作る:私は下の投稿のコードで、C++でリンクリストを作成する方法を練習してる

main.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; 

} 

list.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); 

} 





} 

+0

は' '実際に、それは常にfalseとなります – Wentao

+0

@Rahnをtrue'をし、それがさらにNULLに' head'を設定します。 – immibis

+0

実際の指摘に加えて、一貫したインデントがないと、このコードはほとんど読めなくなります。 –

答えて

0

私は、ノードを追加するときに、故障を得ていると推定。

私が見る問題は、最初の挿入後、あなたは頭を適切に割り当てられているということですが、何も尾のために行われていません。あなたの頭が有効なので次回の挿入では、 '第2ノードを作る'コードブロックに入ります。ここでまだ初期化されていないテールメンバーを参照解除しようとしています。 (ヘッド= 0) `必ず戻ってくる場合

+0

フィードバックをお寄せいただきありがとうございました。私のインデントについて教えていただきありがとうございます。 –

関連する問題