c - 不知道为什么我在这里遇到段错误

标签 c list linked-list segmentation-fault nodes

我知道我可以更改代码来修复错误,但我不明白为什么会出现段错误。感谢所有帮助,谢谢。

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 永远不会得到满足。事实上,您可以看到在段错误发生之前,在最后一个数字 (9) 之后打印了一些垃圾数字 (0)。

当你这样做时:

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

您还应该添加如下内容:

tmp->next->next = NULL;

通过这种方式,您可以“安全”地初始化每个节点,并将 next 指针设置为 NULL。除最后一个节点之外的所有节点都将在下一次迭代中获得正确的值。

编辑 正如 @Someprogrammerdude 在评论中指出的,即使您按照上面的建议进行操作,您最终也会在最后得到一个额外的节点。 要解决这个问题,您可以按如下方式更改创建循环:

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

关于c - 不知道为什么我在这里遇到段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56620981/

相关文章:

c - 链表元素在 for 循环中更新不佳

c - 如何使用 openssl 在 C 代码中进行相互 tls 身份验证?

java - 如何保存ArrayList <List>

c++ - slist 优于 vector 的好处?

list - Haskell:列表理解

c++ - 编辑链表中的数据错误: no match for operator==

java - 检查链表中每个节点的值是否等于 String

c - 如何将 Perl 转换为 C?

c - 添加结构代码后,Valgrind 无效写入

c - 如何使用循环在一行中打印三个数字从 1 到 9