【问题标题】:Workaround for null pointer dereference?空指针取消引用的解决方法?
【发布时间】:2021-03-20 06:46:25
【问题描述】:

我正在回答hackerrank 上的一个编程问题,因此不允许使用类代码和后订购功能之外的任何内容。这个问题是一个简单的后序遍历问题。一段时间后我正在使用c ++,并且由于类结构是用一个指针作为二叉树的左右节点写出的,如果我试图找到一个树节点的邻居的值,他们碰巧是null,我会得到一个分段错误。

到目前为止,这是我的代码:

#include <bits/stdc++.h>

using namespace std;

/* you only have to complete the function given below.  
Node is defined as  

class Node {
    public:
        int data;
        Node *left;
        Node *right;
        Node(int d) {
            data = d;
            left = NULL;
            right = NULL;
        }
};

*/


    void postOrder(Node *root) {
        if(root->left == nullptr && root->right == nullptr)
        {
            return;
        }
        
        postOrder(root->left);
        postOrder(root->right);
        cout << root->data << endl;
    }

}; //End of Solution

我该如何解决这个问题?

【问题讨论】:

  • 解决方法是:不要取消引用空指针。
  • 检查 root 而不是它的孩子。
  • #include &lt;bits/stdc++.h&gt;using namespace std 都是你应该立即改掉的两个习惯。使用您需要的标题。拥抱std:: 前缀。

标签: c++ class reference c++17 nullptr


【解决方案1】:

if(root-&gt;left == nullptr &amp;&amp; root-&gt;right == nullptr) 不足以检查 either 是否为 nullptr:因此如果其中一个节点恰好是 nullptr,则程序的行为未定义。

if (root->left) postOrder(root->left);
if (root->right) postOrder(root->right);

是一个修复;完全删除第一个 if 语句。

另一个解决方法可能是在函数本身的开头检查 if (root),这取决于函数最初的调用方式。

【讨论】:

    【解决方案2】:

    你应该在引用它之前检查指针:

    void postOrder(const Node *root)
    {
        if (root == nullptr) {
            return;
        }
        postOrder(root->left);
        postOrder(root->right);
        std::cout << root->data << std::endl;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-21
      • 2013-02-20
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多