【问题标题】:Exception thrown: write access violation. temp was nullptr抛出异常:写访问冲突。 temp 为 nullptr
【发布时间】:2020-01-06 05:24:12
【问题描述】:

我在else 语句中的insert() 函数中遇到错误。

这是结构:

struct Node
{
    int data;
    Node* next;
};
Node* head = NULL;

这里是函数:

void insert(int data)
{
    Node* New = new Node();
    if (head == NULL)
    {
        New->data = data;
        head = New;
    }
    else
    {
        // down here where the error occured
        Node* temp = new Node();
        temp = head;
        while(temp != NULL)
        {
            temp = temp->next;
        }
        temp->data = data;
        temp->next = New;
    }
}

【问题讨论】:

    标签: c++ c++14


    【解决方案1】:

    你的循环:

    while(temp != NULL)
    

    temp 等于nullptr 时终止(请注意,您最好在C++ 中使用此常量而不是NULL)并在该循环之后立即取消引用temp。同样没有任何理由将new 的结果分配给temp 并立即将其释放到下一行代码(导致内存泄漏)。而且您应该始终将data 分配给新项目,而不是temp(假设是最后一项)您的逻辑应该是这样的:

    void insert(int data)
    {
        Node* New = new Node();
        New->data = data;     // note you better do these 2 lines in constructor
        New->next = nullptr; 
        if (head == nullptr)
        {
            head = New;
            return;
        }
        Node* temp = head; 
        while( temp->next != nullptr ) // look for the last item
            temp = temp->next; 
        temp->next = New;
    }
    

    【讨论】:

    • 然后代码可以大大简化:void insert(int data) { Node **temp = &head; while (*temp) { temp = &((*temp)->next); } *temp = new Node{data, nullptr}; }
    • @RemyLebeau 同意,但这对于 OP 来说可能太复杂了,看起来指针不是他的强项,这里甚至是指向指针的指针。
    猜你喜欢
    • 2022-12-20
    • 2020-04-15
    • 1970-01-01
    • 2020-09-12
    • 2021-07-12
    • 2016-08-01
    • 2016-08-25
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多