如何在C中为链表头分配空间?

use*_*628 0 c valgrind linked-list

    struct node {
        int data;
        struct node *next;
    };

    int main() {

        struct node *head = malloc(sizeof(struct node));
        struct node *current = head;
        ...
    };
Run Code Online (Sandbox Code Playgroud)

虽然这段代码可以在没有任何警告或错误的情况下运行,但Valgrind会给出一些消息Conditional jump or move depends on uninitialised value(s),Uninitialised value was created by a heap allocation

我无法弄清楚出了什么问题.我们在node函数外定义了一个struct main.所以我认为我们可以使用sizeof(struct node),不是吗?

Loc*_*ran 5

您需要使用head初始化数据和下一个指针.我的意思是

head->data = 0;
head->next = NULL;
Run Code Online (Sandbox Code Playgroud)

它将通过Valgrind检查