【发布时间】:2014-01-25 18:43:18
【问题描述】:
以下 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);
}
【问题讨论】:
-
编译时包含所有警告和调试信息 (
g++ -Wall -g)。然后使用调试器 (gdb)
标签: c++ linked-list segmentation-fault initialization singly-linked-list