gpt4 book ai didi

c - 通过链表迭代导致段错误

转载 作者:太空宇宙 更新时间:2023-11-04 05:07:49 24 4
gpt4 key购买 nike

我只是写了一个简单的链接列表,但是当通过 add()display() 遍历列表时,程序出现段错误。

#include <stdlib.h>
#include <stdio.h>

typedef struct entry {
void *value;
struct entry *next;
} entry;

typedef struct list {
entry *items;
} list;

list *create(void) {
list *l;

l = malloc (sizeof(list));
l->items = malloc(sizeof(entry*));
l->items->next = NULL;

return l;
}

void add(list *l, void *value) {
entry *temp, *last, *new;

for (temp = l->items; temp != NULL; temp = temp->next) {
last = temp;
}

new = malloc(sizeof(*new));

new->value = value;
new->next = NULL;

last->next = new;
}

void display(list *l) {
entry *temp;

for (temp = l->items; temp != NULL; temp = temp->next) {
printf("%s\n", temp->value);
}
}

int main(void) {
list *l = create();

add(l, "item1");
add(l, "item2");
add(l, "item3");
add(l, "item4");

display(l);

return 0;
}

我已经在几台机器上测试了代码,它可以在一些机器上运行,而在其他机器上不能运行。我对错误的来源一无所知。

最佳答案

这没有分配足够的空间:

l->items = malloc(sizeof(entry*));

它应该是 sizeof(entry),或者如果您想遵循您在别处使用的模式:

l->items = malloc(sizeof(*l->items));

因此,您当前正在践踏内存。

关于c - 通过链表迭代导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10887260/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com