簡體   English   中英

不知道為什么我在這里遇到細分錯誤

[英]Not sure why I am getting a segmentation fault here

我知道我可以更改代碼來修復錯誤,但是我不明白為什么我會遇到細分錯誤。 感謝所有幫助,謝謝。

typedef struct nodes{
    int data;
    struct nodes *next;
} node;

int main(int argc, char * argv[]){
    node *head = NULL;
    node *tmp = NULL;
    int i;

    head = malloc(sizeof(node));
    tmp = head;
    for(i = 0; i < 10; i++){
        tmp->data = i;
        tmp->next = malloc(sizeof(node));
        tmp = tmp->next;
    }
    tmp = NULL;
    for(tmp=head; tmp->next != NULL; tmp = tmp->next){
        printf("%d\n", tmp->data);
    }

}

這是輸出:

0
1
2
3
4
5
6
7
8
9
0
Segmentation fault: 11

最后一個節點的next指針未設置為null 因此,永遠不會滿足第二個for tmp->next != NULL的條件tmp->next != NULL 實際上,您可以看到在出現段錯誤之前,在最后一個數字( 9 )之后打印了一些垃圾數字( 0 )。

執行此操作時:

tmp->next = malloc(sizeof(node));

您還應該添加以下內容:

tmp->next->next = NULL;

這樣,您可以“安全地”初始化每個節點,並將next指針設置為NULL 除最后一個節點外,所有節點都將在下一次迭代中獲得正確的值。

由@Someprogrammerdude在注釋中指出的EDIT ,即使您執行了上面建議的操作,也將最終在最后增加一個節點。 要解決此問題,可以按如下所示更改創建循環:

for(i = 0; i < 10; i++){
    tmp->data = i;
    if (i < 9) {
        tmp->next = malloc(sizeof(node));
    } else {
        tmp->next = NULL;
    }
    tmp = tmp->next;
}

通過向后構建列表,您將獲得更簡潔的代碼。 換句話說,首先將最后一個節點添加到列表中,然后在列表的開頭插入其他節點。 代碼如下:

node *head = NULL;
for (int i = 9; i >= 0; i--)
{
    node *tmp = malloc(sizeof(node));
    tmp->data = i;
    tmp->next = head;
    head = tmp;
}

請注意,由於head最初為NULL ,因此列表中的最后一個節點的next指針將設置為NULL 那就是您的代碼中所缺少的。

暫無
暫無

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

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