通过链表进行迭代会导致分段错误

thp*_*rus 0 c list

我只是编写了一个简单的链表,但是当通过列表迭代add()并且display()程序seg出错时.

#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;
}
Run Code Online (Sandbox Code Playgroud)

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

Fat*_*ror 6

这没有分配足够的空间:

l->items = malloc(sizeof(entry*));
Run Code Online (Sandbox Code Playgroud)

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

l->items = malloc(sizeof(*l->items));
Run Code Online (Sandbox Code Playgroud)

结果,你现在正在践踏记忆.