-4

以下C++代碼引發了分段錯誤錯誤。當只有一個鏈表被創建並顯示時,所有的工作文件。但介紹第二個列表後會導致錯誤。 這裏的目標是創建並顯示兩個鏈接列表。創建兩個鏈接列表時出現分段錯誤

#include<iostream> 
using namespace std; 
struct node { 
    int value; 
    node* link; 
}; 

void insert_into_list(node** head, int value) { 
node* temp = new node; 
temp->value = value; 
temp->link = (*head); 
(*head) = temp; 

} 
void display_link(node* he) { 
cout << "Link List:\n"; 
node* head = he; 
while (head != NULL) { 
    cout << head->value; 
    if (head->link != NULL) 
     cout << "->"; 
     head = head->link; 
} 
cout << endl; 
} 

int main() { 

    node* head1; 
    node* sec; 
    insert_into_list(&head1, 9); 
insert_into_list(&head1, 7); 
insert_into_list(&head1, 6); 

display_link(head1); 
cout<<"LKL"<<endl; 


insert_into_list(&sec, 8); 
insert_into_list(&sec, 6); 
insert_into_list(&sec, 7); 

display_link(sec); 

} 
+5

編譯。然後**使用調試器**('gdb') –

回答

2

程序具有不確定的行爲,因爲變量

node* head1; 
    node* sec; 

未初始化。

改用

node* head1 = 0; 
node* sec = 0; 
-3

這是它的工作對head1一個謎。

你應該給你的清單一個適當的結局。

node* head1 = 0; 

也將幫助自己,如果你使用的所有警告和調試信息(`G ++ -Wall -g`)提供您的node有一個構造函數,像

node(int value, node* next); 
+0

否_'mystery'_只是UB ... –