0
votes

My code below successfully converts a Binary search tree to a linked list however valgrind has been giving me "Conditional jump or move depends on uninitialised value(s)" errors. Yet after looking at my code, I don't see where I have that?

ListNodePtr convertBSTtoLinkedList(TreeNodePtr root)
{
    ListNodePtr list,head;
    list = malloc(sizeof(struct ListNode));
    list->key = root->key;
    if (root->right != NULL)
    {
        list->next = convertBSTtoLinkedList(root->right);    //line 80
    }
    if (root->left != NULL)  
    {
    ListNodePtr tail;
    head = convertBSTtoLinkedList(root->left);   //line 85
    tail = head;
    while (tail->next != NULL) {        //Line 87
        tail = tail->next;
    }
    tail->next = list;
    return head;
    }
    return list;
}   

This is my valgrind error, it repeats itself a few times.

==3076== Conditional jump or move depends on uninitialised value(s)
==3076==    at 0x108AF2: convertBSTtoLinkedList (bst.c:87)
==3076==    by 0x108AC8: convertBSTtoLinkedList (bst.c:80)
==3076==    by 0x108ADD: convertBSTtoLinkedList (bst.c:85)
==3076==    by 0x108ADD: convertBSTtoLinkedList (bst.c:85)
==3076==    by 0x108ADD: convertBSTtoLinkedList (bst.c:85)
==3076==    by 0x108AC8: convertBSTtoLinkedList (bst.c:80)
==3076==    by 0x108AC8: convertBSTtoLinkedList (bst.c:80)
==3076==    by 0x108754: main (main_bst.c:28)
1
What is line 80 etc.M.M
I have added comments.TheShield
Where is the NULL check for root ptrPotato
list->key = root->key; did you check for root == NULL ?Potato
Do you mean if a NULL root was passed to the function? If so, I added a check and it did not fix the errors.TheShield

1 Answers

2
votes

malloc gives you a pointer to uninitialized memory. So unless you set each member of your ListNode struct, trying to access that member later is a bad idea.

When your convertBSTtoLinkedList function processes any node of the BST which does not have a right child, it fails to set next on the created list node. So the next time after that a higher level in the recursion attempts to find the end of the returned sublist, it walks to the end of the sublist, checks that uninitialized next pointer, and valgrind complains.