2014-01-29 77 views
0

我想一個節點添加到一個單向鏈表的結尾,但我得到一個分割故障(核心轉儲錯誤)添加節點到端單向鏈表

void slist_add_back(struct slist *l, char *str) 
{ 

    struct snode *temp; 

    do{ 
     l->front = l->front->next; 
     l->counter++; 

    }while(l->front !=NULL); 

    l->counter++; 
    temp = (struct snode *)malloc(sizeof(struct snode)); 
    l->back = l->front; 
    l->back->next = temp; 
    l->back = temp; 
} 
+0

你似乎只增加了一個元素而增加了計數器。 – chris

+0

這是比C++更多的C代碼。 –

+2

'front'代表你的列表的前面嗎?如果是這樣,你不想因爲你在這裏添加另一個元素而改變它。 – tabstop

回答

1

當你寫:

do{ 
     l->front = l->front->next; 
     l->counter++; 

    }while(l->front !=NULL); 

最後l->front爲空。現在l->back = l->front;意味着l->back也是null。因此,這種分配是錯誤的:

你的問題
l->back->next = temp; // causing segfault 
0

一個就在這裏:

do 
{ 
    l->front = l->front->next; 
    l->counter++; 
} while(l->front !=NULL); 

你是不是修改迭代它的列表。它應該是這樣的:

snode* curr = l->front; 
if (curr == NULL) // first element 
{ 
    front = new snode(str); 
    return; 
} 

while (curr->next != NULL) 
{ 
    ++curr; 
} 
curr->next = new snode(str); // or the malloc version if you want to stay in C 
+0

這是C,沒有'new'。 –

+0

@KarolyHorvath他原來的標籤是C++(因此我對OP和代碼示例都有評論)。 –

0

我想這是你想要的東西? 我真的不明白你的代碼在做什麼,對不起。

void slist_add_back(struct slist *l, char *str) 
{ 


    struct snode *currentNode = l->front; 
    if(currentNode!=NULL) 
    { 
     struct snode *temp = (struct snode *)malloc(sizeof(struct snode)); 
     while(currentNode->next!=NULL) 
     { 
     l->counter++;//although i dont know why 
     currentNode = currentNode->next; 
     } 


     l->counter++;//again 
     currentNode->next = temp; 
     l->back = temp; 
     temp->next = NULL; 
    } 
} 
+2

錯誤:如果'currentNode'爲NULL ... –

+0

尚未調試:P – HenryLok

0

下面是你的代碼大致應該是這樣的:

void slist_add_back(struct slist *l, char *str) 
{ 
    struct snode *temp = malloc(sizeof(struct snode)); 
    temp->next = NULL; 
    //note: store str... (strdup?) 

    if (! l->back) { 
     l->front = temp; 
    } else { 
     l->back->next = temp; 
    } 
    l->back = temp; 
    l->counter++; 
} 

注:根據您的代碼,我會很驚訝,如果其餘的將不會是完全錯誤的,所以除了崩潰即使這部分是固定的...

選擇一個調試器,並檢查你的代碼真的