【发布时间】:2014-02-13 06:55:38
【问题描述】:
我刚刚开始学习 C,并且正在研究链表的简单实现。当我尝试打印我的清单时,我意识到了一些奇怪的事情。即使该代码从未执行过,我也会在部分代码中遇到分段错误。这怎么可能?
据我所知,while 循环永远不会执行,因为 next 指针不指向任何东西。我在想,也许在评估 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;
}
【问题讨论】:
标签: c pointers crash linked-list segmentation-fault