簡體   English   中英

拋出異常:寫訪問沖突。 temp 為 nullptr

[英]Exception thrown: write access violation. temp was nullptr

我在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;
    }
}

你的循環:

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM