'Valgrind: Conditional jump or move depends on uninitialised value. Check is null. C
I have this code:
// list.h
typedef struct Node {
struct Node *next;
int *data;
} Node;
typedef struct List {
Node *head;
} List;
// main.c
#include <stdio.h>
#include <stdlib.h>
#include "helpers.h"
int main()
{
// creating list
List *list = (List*)malloc(sizeof(List));
Node *node = (Node*)malloc(sizeof(Node));
list->head = node;
// creating 5 empty nodes
for (int i = 1; i < 5; i++)
{
node->next = (Node*)malloc(sizeof(Node));
node = node->next;
}
// trying to fill it if it is empty
node = list->head;
for (int i = 1; i < 5; i++)
{
if (node->data == NULL)
{
node->data = (int*)malloc(sizeof(int));
*(node->data) = 1;
}
}
// freeing
node = list->head;
Node *tmp;
while (node != NULL)
{
free(node->data);
tmp = node;
node = node->next;
free(tmp);
}
free(list);
return 0;
}
I am trying to use valgrind and this is what he tells:
==340== Conditional jump or move depends on uninitialised value(s)
==340== at 0x10870A: main (main1.c:24)
I don't strictly need to have something inside node, so my list can be like this [1,1, null, 1, null]. But then in the code I want to use if statement to check if node->data is already exists (this is a pointer, so I have to check if memory allocated and data points to some value).
To be honest my program is working somehow (it is more complicated than this example code I showed, but the valgrind error is similar), but I think something goes wrong anyway.
Solution 1:[1]
you must terminate your linked list with a NULL, so after creation the last node should lastnode->next == NULL, therefore when done creating you must initialise it with NULL lastnode->next = NULL;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Moe Assaf |
