简体   繁体   中英

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. I never set new to RootNode, so it's simply a null pointer the first time this runs through. However, when I try to check if it's null (via currNode), it keeps coming up false and saying it's not null. Therefore, that first if statement never goes through. 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.

Why is this happening? I tried valgrind but it just tells me that there's no malloc/free/etc. via the address where RootNode is at. 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. So what do I do?

be sure you have initialized your RootNode to null before:

WordNode* RootNode=NULL;

if this is done, be sure that this constructor is being called before and that you operate on initialized instance

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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