【问题标题】:I keep getting segmentation fault on link list我不断在链接列表上遇到分段错误
【发布时间】:2016-08-03 21:18:17
【问题描述】:

该程序应该生成用户输入的n 数字的随机链表,但是当它尝试打印链表时会出现分段错误。

程序一直工作到必须显示链表为止。

#include <iostream>

class node
{
public:
    // TYPEDEF
    typedef double value_type;

    // CONSTRUCTOR
    node(
         const value_type& init_data = value_type(),
         node* init_link = NULL
         )
    { data_field = init_data; link_field = init_link; }

    // Member functions to set the data and link fields:
    void set_data(const value_type& new_data) { data_field = new_data; }
    void set_link(node* new_link)             { link_field = new_link; }

    // Constant member function to retrieve the data:
    value_type data() const { return data_field; }

    // Constant member functions to retreive the link:
    node* linker() const          { return link_field; }

private:
    value_type data_field;
    node* link_field;
};

int myrand(int)
{
    return(1 + rand() %(1000 - 1 +1));
}

void print_linked_list(node*& head_ptr, node*& print_ptr, size_t n)
{
    for (size_t i =1 ; i <= n ; i++) {
        head_ptr = new node(myrand(n), head_ptr);
    }
    std::cout << "Unsorted List: " << std::endl;
    for (print_ptr = head_ptr; print_ptr !=NULL; print_ptr = print_ptr->linker()) {
        std::cout <<  print_ptr->data() << " ";
    }
}

int main()
{
    size_t n;
    srand(time(NULL));

    node* head_ptr;
    node* print_ptr;

    std::cout << "Please input a number" << std::endl;
    std::cin >> n;

    print_linked_list(head_ptr, print_ptr, n);

    return 0;
}

【问题讨论】:

    标签: c++ linked-list segmentation-fault fault


    【解决方案1】:

    您正试图访问一个未初始化的指针。您为 print_linked_list 函数提供了未初始化的 head_ptr 变量。然后它在创建第一个节点时使用该值作为指向下一个节点的指针。这意味着条件print_ptr != NULL 永远不会满足。

    这可以通过在main 中声明时将head_ptr 设置为NULL 来解决。

    【讨论】:

    • 附带说明,您也有内存泄漏,因为您永远不会删除使用new 创建的节点。
    【解决方案2】:

    head_ptr 未初始化为 NULL

    因此,创建的第一个节点将为其link_field 获取垃圾指针。

    因此,当您的打印代码尝试遍历链接列表时,它最终会碰到垃圾指针,然后跳华尔兹进入永无止境。

    【讨论】:

    • 如果你用nullptr就好了。 ...至少要推广更惯用的方式。 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    相关资源
    最近更新 更多