c - HW3.exe : 0xC0000005: Access violation reading location 0x00000004 中 0x012351CF 处出现未处理的异常

标签 c binary-search-tree

我已经实现了(ADT)二叉剪切树,我必须做一个函数来计算三个儿子之间差异小于五的 parent 的数量。程序可以运行,只有这个函数失败。

在“返回”(递归)时我得到了一个断点。

int difference(BSTNode *root, comperFunc cmpFn, comperFunc lesserThenFive)
{
    int count = 0;
    if (root)
    {
        count = 0;
        if (root->Left && root->Right)
        {
            //if root->Right > root->Left
            if (cmpFn(root->Right->key, root->Left->key) == 1)
            {
                if (lesserThenFive(root->Right->key, root->Left->key))
                     count = 1;  
            }
            //if root->Right < root->Left
            if (cmpFn(root->Right->key, root->Left->key) == -1)
            {
                if (lesserThenFive(root->Left->key, root->Right->key))
                    count = 1;    
            }
       }
   }
   return difference(root->Left, cmpFn, lesserThenFive) + difference(root- >Right, cmpFn, lesserThenFive) + count;//here is the break point

}

最佳答案

在您的 return 语句中,如果您输入 difference 并且 root 为空,您将取消引用空指针。

该返回值需要位于 if block 内,并且您需要在 else 部分返回一些合适的值。

稍微扩展一下。您的算法递归地使用当前root的左右节点调用difference,但最终是root->leftroot-之一>right 将是 NULL。然后,您的 return 语句将有效地尝试使用 NULL 的左侧或右侧成员调用 difference,例如NULL->左。这将在任何现代操作系统上出现错误。

关于c - HW3.exe : 0xC0000005: Access violation reading location 0x00000004 中 0x012351CF 处出现未处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46470839/

相关文章:

c++ - 如何阻止来自 cURL 库的 Qt 应用程序信号 SIGSEGV?

c - C 中的结构初始化错误 : expected expression

c - 在 C 的邻接矩阵中回溯?

java - 使用 T 扩展 Comparable<T> java 检查 BT 是否为 BST

algorithm - 给定一个平衡的 BST。 a min, max, and value,如何找到min和max中最大的Xor?

c - C 中的 BST 链表 : Breadth First Search

c++ - 如何让不同的进程使用Windows 7不同的网络接口(interface)?

c - 在 OpenSSL 中定义常量 BIGNUM

algorithm - 打印二叉树的边界

c++ - 使用递归的 BST 中序遍历