【问题标题】:Segmentation fault when creating two link lists创建两个链接列表时出现分段错误
【发布时间】: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


【解决方案1】:

你的程序有未定义的行为,因为变量

node* head1;
    node* sec;

未初始化。

改为使用

node* head1 = 0;
node* sec = 0;

【讨论】:

    【解决方案2】:

    它对head1有效是个谜。

    你应该给你的列表一个合适的结尾。

    node* head1 = 0;
    

    如果您为node 提供构造函数,您也会帮助自己,例如

    node(int value, node* next);
    

    【讨论】:

      猜你喜欢
      • 2016-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      • 2014-05-19
      • 1970-01-01
      • 2013-02-01
      相关资源
      最近更新 更多