开发者

Code breaks when I don't output the variable; works when I do. WHUT?

I don'开发者_如何学运维t really know what more to say about this.

I have never, ever seen this happen. And it just boggles me what causes this. I figured you guys might have seen this before and now what silly thing I am doing.

Notes about it: 'temp' is a variable the function is taking in. It is a Binary Tree Node (BTN). temp->d accesses the data. ->l is left child, ->r is right child. ->p is parent

NOTE: THIS IS HOMEWORK. IT IS FOR A PRIORITY QUEUE.

NOTE2: I have looked at similar questions. All have suggested a timing error and the 'cout' 'slows' the code down. What would cause this? I can't think of any really 'costly' things I am doing.

  BTN<generic>* nTemp;
  cout << "Sdf\n";
  if(temp->r != NULL)
  {
    if(temp->l != NULL)
        {
          if(*(temp->r->d) > *(temp->l->d))
          {
            if(*(temp->r->d) > *(temp->d))
                {
                  cout << "ASDfs5: " << *(temp->d) << "\n";  //THIS IS WHAT KEEPS IT FROM BREAKING / SEGFAULTING
                  nTemp->d = temp->d; //THIS IS WHERE IT BREAKS (SEGFAULT)
                  cout << "ASDfs\n";
                  temp->d = temp->r->d;
                  cout << "ASDfs4\n";
                  temp->r->d = nTemp->d;
                            cout << "ASDfs3\n";
                  if(temp->r != NULL)
                  {
                    checkPopValues(temp->r);
                            cout << "ASDfs2\n";
                  }
                }
          }
          else
          {
            if(*(temp->l->d) > *(temp->d))
                {
                  nTemp->d = temp->d;
                  temp->d = temp->l->d;
                  temp->l->d = nTemp->d;
                  checkPopValues(temp->l);
                }
          }
        }
        else
        {
          if(*(temp->r->d) > *(temp->d))
          {
            nTemp->d = temp->d;
                temp->d = temp->r->d;
                temp->r->d = nTemp->d;
                checkPopValues(temp->r);
          }
        }
  }
  else
  {
    cout << "sdfs\n";
    if(temp->l != NULL)
        {
          if(*(temp->l->d) > *(temp->d))
      {
            nTemp->d = temp->d;
                temp->d = temp->l->d;
                temp->l->d = nTemp->d;
                checkPopValues(temp->l);
          }
        }
  }
}


You aren't assigning anything to nTemp. It's pointing to garbage.

When you access it on the line that breaks, undefined behavior occurs. If you're lucky, you should get an access violation/segfault. If you're not lucky, it will silently 'work' but probably give you wrong results.

You need to assign a pointer to an existing BIN<Generic> to it or create a new one.


Make sure nTemp is initialized. I bet it isn't. The cout causes something "benign" to be placed in nTemp.


nTemp is not allocated any space so you are writing to random memory.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜