0
    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?

user8314628
  • 1,952
  • 2
  • 22
  • 46
  • Usually the head of a linked list is just a pointer, not a `struct` and so it doesn't require any memory allocation. Its value will be `NULL` (empty list) or a valid pointer to the first node. – Weather Vane Feb 01 '19 at 19:48
  • @WeatherVane's comment about the head of the list is correct, but every node allocation for the list using the above method will generate the same complaint from Valgrind, so there is a good question here. – dmckee --- ex-moderator kitten Feb 01 '19 at 19:53
  • @WeatherVane I modified it as `struct node *head`; then `struct node *current = malloc(sizeof(struct node));` then it comes up with `segamentation falut(core dumped)`. – user8314628 Feb 01 '19 at 19:56
  • 1
    1) malloc returns `void*`, you need to cast it to `(node*)` 2) malloc does not initialize memory, so you need to do it. `memset(head, 0, sizeof(struct node);` – Hedgehog Feb 01 '19 at 20:07
  • 1
    @Hedgehog in C you don't *need* to cast it. Please see [Do I cast the result of malloc?](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Weather Vane Feb 01 '19 at 20:34
  • @Hedgehog Generally if you are going to bulk initialize dynamically allocated memory you should consider using `calloc` instead of `malloc`. – dmckee --- ex-moderator kitten Feb 01 '19 at 22:02
  • regarding `};` at the end of `main()` There should be no semicolon the semicolon causes a compile warning: '11:6: warning: ISO C does not allow extra ‘;’ outside of a function [-Wpedantic]" – user3629249 Feb 03 '19 at 02:18
  • the posted code causes the compiler warning: "8:29: warning: incompatible implicit declaration of built-in function ‘malloc’ – user3629249 Feb 03 '19 at 02:22
  • The posted code results in a memory leak because the allocated heap memory is never released via a call to `free()` – user3629249 Feb 03 '19 at 02:23

1 Answers1

5

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

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

It will pass Valgrind check

Loc Tran
  • 1,170
  • 7
  • 15