简体   繁体   English

C ++指针或内存

[英]C++ pointers or memory

My code seems like it should be working given the algorithm, but I'm new to C++ and it seems that these pointers are overwriting themselves when I call insert multiple times. 给定算法,我的代码似乎应该可以工作,但是我对C ++还是陌生的,当我多次调用insert时,这些指针似乎会覆盖自身。 For example, if I call insert with values 1, 3, 5, then the root will be 1 (as expected), but 3 will be overwritten and the right child of the root will have value 5 instead of 3. 例如,如果我用值1、3、5调用insert,则根将为1(按预期方式),但是3将被覆盖,并且根的右子级将具有值5而不是3。

virtual bool insert(const Data& item) {
if(root == NULL){
  BSTNode<Data> newNode (item);
  root = &newNode;
  isize++;
  return true;
}
BSTNode<Data>* nextNode = root;
BSTNode<Data>* prevNode = NULL;
bool isLeft;
while(nextNode!=NULL) {
  if (item < nextNode->data) {
    prevNode = nextNode;
    nextNode = nextNode->left;
    //std::cout << prevNode->data;
    isLeft = true;
  }
  else {
    prevNode = nextNode;
    nextNode = nextNode->right;
    //std::cout << prevNode->data;
    isLeft = false;
  }
}
BSTNode<Data> createNode (item);
createNode.parent = prevNode;
if (isLeft) prevNode->left = &createNode;
else prevNode->right = &createNode;
isize++;
return true;
}

You have an invalid pointer due to pointing to a local object which is going to destroy: 由于指向要销毁的本地对象,您有一个无效的指针:

BSTNode<Data> newNode (item);
root = &newNode;

Object newNode is a local object within method insert after returning from this method (it goes out of scope), pointer root will point to a destroyed object. 对象newNode是从此方法返回后超出方法范围的方法insert的局部对象(指针超出范围),指针root将指向已破坏的对象。 A naive possibility to solve the problem is allocating newNode in heap by new : 解决该问题的一种天真的可能性是通过new在堆中分配newNode

root = new BSTNode<Data>(item);

but you must delete it somewhere, and also same issue for createNode . 但是您必须deletedelete ,并且createNode也会出现同样的问题。


As recommended by many, you should use smart-points such as unique_ptr and shared_ptr . 正如许多人所建议的那样,您应该使用智能点,例如unique_ptrshared_ptr

Assuming that root is a member variable, you need to allocate it on the heap and not on the stack: 假设root是成员变量,则需要在堆而不是堆栈上分配它:

if(root == NULL){
  root = new BSTNode<Data>(item);
  isize++;
  return true;
}

Otherwise the node is destroyed once it goes out of scope at the closing brace of the if body. 否则,一旦节点超出if主体的闭合大括号, if该节点将被销毁。 The same goes for 同样的道理

if (isLeft) prevNode->left = new BSTNode<Data>(item);
else prevNode->right = new BSTNode<Data>(item);

I haven't checked your actual insertion logic though. 我还没有检查您的实际插入逻辑。 You should should post the entire code, there is too little here to check it. 您应该发布完整的代码,这里没有太多可以检查的代码。 Is it a binary tree? 它是二叉树吗?

Edit: Don't forget to delete the nodes if you create them on the heap, as per MM's answer. 编辑:根据MM的回答,如果您在堆上创建节点,请不要忘记删除节点。

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

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