2013-07-18 52 views
0
#include<iostream> 
using namespace std; 
class list 
{ 
public: 
    list(); 
    bool insertHead(int n); 
private: 
    struct node 
    { 
     int item; 
     node *next; 
    }; 
    node* head; 
    }; 


list::list() 
{ 
    head = NULL; 
    head -> item = 0; 
    head -> next = NULL; 
} 

bool list::insertHead(int n) 
{ 
    node* tempptr = new node; 
    tempptr->item = n; 
    tempptr->next = head; 
    head = tempptr; 
    return true; 
} 

    int main() 
    { 
      list test1; 
      test1.insertHead(4); 

      return 0; 
    } 

此代碼在運行時編譯好但不幸運行段錯誤。我試圖在insertHead函數的末尾添加刪除tempptr,但無濟於事。在內存分配方面我非常糟糕,我知道分段錯誤與運行時內存分配有關。有誰能夠幫助我?我只是使用insertHead將整數插入鏈表的前面。有人可以幫我嗎?謝謝!我將實現和其他文件組合在一起,因此更易於閱讀......我想。謝謝分段錯誤11鏈接列表節點結構

+0

爲什麼'delete'會解決分段錯誤?另外,你是否嘗試在調試器中運行你的代碼? – 2013-07-18 07:00:41

+0

它在哪裏段錯? – chris

+2

在'list :: list'中,您設置了'head = NULL',然後嘗試對其進行解引用。你期望如何工作? – Barmar

回答

1

創建空列表時,您只需將head設置爲NULL即可。沒有必要設置itemnext,因爲它是一個空列表。您正在取消引用NULL指針,這是不允許的,並且在大多數系統上會導致分段錯誤或類似錯誤。

list::list() 
{ 
    head = NULL; 
} 
2
head = NULL; 
    head -> item = 0; 
*** segmentation fault, beacuse head is null, can't dereference 
    head -> next = NULL; 
+0

如果是迂腐的 - 不一定是段錯誤。這是未定義行爲,任何事情都可能發生。 – soon

0

你真的很驚訝,這段代碼崩潰了嗎?

head = NULL; 
head -> item = 0; 
head -> next = NULL; 

您將NULL指定給指針並立即引用它。

0
head = NULL; 
head -> item = 0; 
head -> next = NULL; 

不可能工作。 ->運算符將指針取消引用,如果其值設置爲NULL,則顯然不可行。你需要預先分配內存頭:

head = new node; 
2

我會建議使用GDB,運行gdb與此程序。當它發生段錯誤時,它會給你一個確切程序段錯誤發生位置的堆棧跟蹤。您可以使用'p命令'打印相關變量。 Seg fault總是意味着訪問超出你的進程範圍的內存(指針的值不在你的進程內 - 無效指針)。學習如何使用GDB會爲您節省大量時間,它是seg故障的解決方案:-)