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

标签 c list

我只是写了一个简单的链接列表,但是当通过 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/

相关文章:

python - 为什么我的类的 __new__() 方法不返回该类的实例?

list - 链表分区函数和反转结果

c++ - 梯度算法产生小白点

C编程: reading and writing binary files

c - 如何将 getchar() 读取的整数保存到数组中?

c++ - 使用指针遍历类的动态分配

C# 列表作为字典键

list - Haskell 任何人都可以通过示例解释deleteFirstsBy 函数如何工作吗?

python - 遍历 python 元组列表并更改值

c - C语言中日期只能输入一个整数,不能输入年月日