我剛剛開始學習C並正在研究鏈接列表的簡單實現。當我嘗試打印我的清單時,我意識到一些奇特的東西。即使代碼從未執行,我也會在代碼的一部分發生分割錯誤。怎麼會這樣?分割錯誤,儘管代碼從未執行?
據我所知,while循環從不執行,因爲下一個指針並不指向任何東西。我在想,也許在評估while循環時,它可能會導致它指向導致分段錯誤的東西,但奇怪的是,如果您刪除了行root = root->next
,它會執行正常(沒有任何錯誤)。即使它不會進入while循環。那麼如果一行代碼(root = root->next
)導致錯誤,如果代碼從未執行?代碼編譯得很好。我在某個地方犯了一個簡單的錯誤嗎?我知道這不是一個適當的鏈接列表實現,它是爲學習目的而進行的。
#include <stdio.h>
#include <stdlib.h>
struct linkedlist {
int value;
struct linkedlist * next;
};
typedef struct linkedlist item;
int main(int argc, char **argv) {
item * root;
item * current;
root = malloc(sizeof(item));
root->value = 500;
int i;
for(i = 0; i <= 20; i++) {
current->next = malloc(sizeof(item));
current = current->next;
current->value = i;
}
while(root->next != 0) {
//This is never executed
printf("[%d]\n", root->value);
//the line below does cause the segmentation error
//but how can this affect anything at all if this is never executed?
root = root->next;
}
return 0;
}
但是,如果我取消對該行的root =根 - >下一步;並在最後輸入一個prinf語句而不會崩潰。 –
root-> next也不會在while循環之前初始化。 – OldProgrammer
@OldProgrammer我可以檢查while循環嗎? while(root-> next!= NULL)? –