简体   繁体   中英

How to allocate space for the head of linked list in C?

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

    int main() {

        struct node *head = malloc(sizeof(struct node));
        struct node *current = head;
        ...
    };

Though this piece of code can run without any warning or error, Valgrind will give some messages saying Conditional jump or move depends on uninitialised value(s) , Uninitialised value was created by a heap allocation

I can't figure out what's going wrong. We defined a node struct outside the main function. So I think we can use sizeof(struct node) , isn't it?

You need to intialize the data and next pointer with head. I mean

head->data = 0;
head->next = NULL;

It will pass Valgrind check

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM