简体   繁体   English

尝试 append 到链表时出现分段错误,c++

[英]Segmentation error when trying to append to linked list, c++

I have a struct defined as such:我有一个这样定义的结构:

struct Node { 
    int day = 0; 
    int number = 0;
    Node* next = nullptr; 
};

and wrote a create function并写了一个创建 function

Node* ll_create(int day, int number){
    Node* p = new Node;
    p->day = day;
    p->number = number;
    p->next = nullptr; 
    return p;
}

but my append function always end up in a segmentation error但我的 append function 总是以分段错误告终

void ll_append(Node* head, int day, int num, int len){
    Node* new_cnode = ll_create(day,num);

    Node* last = head;
    while (last->next != nullptr)
        last = last->next;

    last->next = new_cnode;

}

can someone tell me how to fix this?有人可以告诉我如何解决这个问题吗?

Most probably the root cause of the issue is missing error handling .问题的根本原因很可能是missing error handling ie A basic rule can be followed that: before any pointer is dereferenced, it should be validated.即可以遵循一个基本规则:在取消引用任何指针之前,应该对其进行验证。

void ll_append(Node* head, int day, int num, int len){
    Node* new_cnode = ll_create(day,num);

    Node* last = head;
    while (last->next != nullptr) //Here, last (i.e. head) can be nullptr.
        last = last->next;

    last->next = new_cnode;

}

The decision can be taken wheather the caller to ll_append shall ensure the head or the ll_append itself can validate. ll_append的调用者应确保headll_append本身可以验证,都可以做出决定。

The first solution could look like below:第一个解决方案可能如下所示:

void ll_append(Node*& head, int day, int num, int len){
    Node* new_cnode = ll_create(day,num);
    //Case 1 : When head is pointing to empty list, you can create the first node.
    if(not head)
    {
       head = new_node;
       return;
    }
    //Case 2 : When head is pointing to a valid list (i.e. at least one node is present)
    Node* last = head;
    while (last->next != nullptr)
        last = last->next;

    last->next = new_cnode;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM