简体   繁体   English

segfault指向空指针C ++

[英]segfault to a null pointer C++

WordBinaryTree::WordBinaryTree()
{
   //RootNode is a private WordNode* of WordBinaryTree()
   RootNode = 0; //just to set it to null...
}

void WordBinaryTree::AddNode(WordNode node)
{
  //RootNode is WordNode*, should be null the first time through
  WordNode* currNode = RootNode;

  if (!currNode)
  {
     currNode = new WordNode();
     currNode->Value = node.Value;
     currNode->Word = node.Word;
     RootNode = currNode;
     return;
  }

  while (1)
  {
     if (currNode->Value > node.Value) 
     //other code here......

I'm not quite sure what in the world is wrong with my code. 我不太确定我的代码到底出了什么问题。 I've searched online and nothing is coming up with a solution. 我在网上搜索过,没有解决方案。 WordNode is a type struct and RootNode is simply a pointer to that. WordNode是类型struct,而RootNode只是指向它的指针。 I never set new to RootNode, so it's simply a null pointer the first time this runs through. 我从来没有为RootNode设置new,因此它第一次运行时只是一个空指针。 However, when I try to check if it's null (via currNode), it keeps coming up false and saying it's not null. 但是,当我尝试检查它是否为空(通过currNode)时,它不断出现错误并说它不为空。 Therefore, that first if statement never goes through. 因此,第一个if语句永远不会通过。 This causes a segfault when the if statement in the while loop happens because it's trying to get a value from a null pointer. 当while循环中的if语句发生时,这会导致段错误,因为它试图从空指针获取值。

Why is this happening? 为什么会这样呢? I tried valgrind but it just tells me that there's no malloc/free/etc. 我尝试了valgrind,但它只是告诉我没有malloc / free / etc。 via the address where RootNode is at. 通过RootNode所在的地址。 I know that! 我知道! I'm trying to make a new if it's null (via that if statement) but it just keeps coming up as false, as if the RootNode isn't really null. 我正在尝试创建一个新的是否为空(通过该if语句),但它一直显示为假,好像RootNode并非真正为空。 So what do I do? 那我该怎么办?

be sure you have initialized your RootNode to null before: 确保在以下情况下已将RootNode初始化为null:

WordNode* RootNode=NULL;

if this is done, be sure that this constructor is being called before and that you operate on initialized instance 如果完成此操作,请确保在此构造函数之前被调用,并且您对初始化的实例进行操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM