指针空检查即使未分配空值也计算为true

时间:2018-08-18 10:01:56

标签: c++ pointers binary-tree

这是用于创建二叉树的代码,它执行得很好。我不了解的是,在我看来,entry函数内a.entry[i][j]=in.nextInt(); 语句的temp->left==NULLtemp->right==NULL条件如何被评估为if() ,这应该引发分段错误,因为我没有在任何地方初始化节点insert(string)的{​​{1}}或TRUE指针。

left

以下是输出:

right

要检查它是否确实是UB还是NULL运算符的作用,我运行了一个测试代码:

#include<iostream>
using namespace std;

class node
{
  public:
    string data;
    node *left,*right;
};

class btree
{
  private:
    node *root;

  public:
    btree()
    {
      root=NULL;
    }
    void create();
    void insert(string);
};

void btree:: create()
{
  cout<<"\n\nEnter the no. of nodes you want to create: ";
  int n;
  cin>>n;
  cin.ignore();
  for(int i=0;i<n;i++)
  {
    cout<<"\nEnter data for node "<<i+1<<": ";
    string input;
    getline(cin,input);
    insert(input);
  }
}

void btree:: insert(string str)
{
  if(root==NULL)
  {
    root=new node;
    root->data=str;
    return;
  }
  node *temp=root;
  while(temp!=NULL)
  {
    cout<<"\n\nDo you want to enter the node in the left subtree or the right subtree of "<<temp->data<<"?(l/r): ";
    char dir;
    cin>>dir;
    cin.ignore();
    if(dir=='l')
    {
      if(temp->left==NULL)
      {
        temp->left=new node;
        temp->left->data=str;
        return;
      }
      else
        temp=temp->left;
    }
    if(dir=='r')
    {
      if(temp->right==NULL)
      {
        temp->right=new node;
        temp->right->data=str;
        return;
      }
      else
        temp=temp->right;
    }
  }
}

int main()
{
  btree bt;
  bt.create();

  return 0;
}

测试代码的输出:

Enter the no. of nodes you want to create: 3

Enter data for node 1: 5

Enter data for node 2: 1


Do you want to enter the node in the left subtree or the right subtree of 5?(l/r): l

Enter data for node 3: 9


Do you want to enter the node in the left subtree or the right subtree of 5?(l/r): r

因此,测试代码似乎可以识别UB并引发段错误。为什么不输入第一个代码?

我尝试搜索类似的问题,但找不到。

1 个答案:

答案 0 :(得分:0)

您应明确leftright初始化为NULL0nullptr(最好是{{1} }。正如其他评论者所提到的,当指针未初始化时,很有可能出现未定义的行为。

最佳做法(IMHO):

nullptr
相关问题