不知道为什么valgrind给我条件跳转或移动取决于未初始化的值(s)错误?

时间:2017-11-16 04:00:57

标签: c valgrind

下面的代码成功地将二进制搜索树转换为链接列表,但是valgrind一直在给我"条件跳转或移动取决于未初始化的值"错误。看了我的代码后,我不知道我在哪里?

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;
}   

这是我的valgrind错误,它会重复几次。

==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 个答案:

答案 0 :(得分:2)

malloc为您提供指向未初始化内存的指针。因此,除非您设置ListNode结构的每个成员,否则稍后尝试访问该成员是一个坏主意。

当您的convertBSTtoLinkedList函数处理BST中没有正确子节点的任何节点时,它无法在创建的列表节点上设置next。所以下一次在递归后的更高级别尝试查找返回子列表的结尾时,它会走到子列表的末尾,检查未初始化的next指针,并且valgrind会抱怨。

相关问题