簡體   English   中英

為什么此pop()函數會產生段錯誤?

[英]Why is this pop() function creating a seg fault?

我有類stackLL ,而pop()函數在主體中使用時會創建seg錯誤。 這是代碼:

這是結構和類的定義:

struct llNode{
int data;
llNode* next;
};

class stackLL{
public:
stackLL();
void push(int x);
int pop();
void print();

private:
llNode* head;
};

這是成員函數定義:

int stackLL::pop(){
    if (head == NULL){
    return false;
    }

    else {
    llNode *tmp= new llNode;
    cout<<"The integer is: "<<head -> data;
    tmp = head;
    head = tmp -> next;
    delete tmp;
    return tmp -> data;

    }
}

這是主要的實現:

stackLL sll;

幾行

 sll.pop();
delete tmp;
return tmp -> data;

您將在返回數據之前刪除tmp 您正在有效地返回不存在或已經失效的數據。
動態分配tmp是不必要的。 您可能只是自動分配了tmp (即llNode tmp = head; )。 那也將擺脫段錯誤。

另外, pop的代碼可能沒有按照您的意圖做(或者至少沒有做鏈表的pop函數會做的事情)。

此外,您永遠不要使用空白的newdelete (容易出錯)。 而是使用智能指針之一,最好是std::unique_ptr<...>ùnique_ptr沒有引用計數器)

您是否為段錯誤感到驚訝?

delete tmp;
return tmp -> data;

在重新建立temp-> data之前,在pop()函數中,您實際上是在刪除該temp節點。 這就是您遇到分段錯誤的原因。

暫無
暫無

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

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