我打算使用有序数组来构建平衡二叉搜索树。一切进行得很顺利,直到程序结束。似乎二叉搜索树的析构函数出了一些问题。
错误信息:
非常感谢!
错误信息:
程序收到EXC_BAD_ACCESS信号,无法访问内存。 原因:KERN_PROTECTION_FAILURE,地址为0x00007fff5f3ffff8 0x0000000100002857在BST_Node.h:18中的~BST_Node(this=0x100100920)中 ~BST_Node() {delete parent; delete left; delete right;}
#ifndef BST_NODE_H
#define BST_NODE_H
#include <cstddef>
class BST_Node {
public:
BST_Node(int k) : key(k), parent(NULL), left(NULL), right(NULL) {}
~BST_Node() {if (parent!=NULL) delete parent;if (left!=NULL) delete left;if (right!=NULL) delete right;}
// data member
int key;
BST_Node* parent;
BST_Node* left;
BST_Node* right;
};
#endif
#include <iostream>
#include <vector>
#include "BST_Tree.h"
#include "BST_Node.h"
using namespace std;
// use recursion to construct the tree. Find the mid of the array to be the root of the subtree. Use left part of the array to construct the left subtree and right part to construct the right subtree.
BST_Node* CreateTree(vector<int> &a, int start, int end) {
if (end<start) {
return NULL;
} else {
int mid = (start+end+1)/2;
BST_Node* p = new BST_Node(a[mid]);
BST_Node* l_tmp = CreateTree(a, start, mid-1);
if (l_tmp)
l_tmp->parent = p;
p->left = l_tmp;
BST_Node* r_tmp = CreateTree(a, mid+1, end);
if (r_tmp)
r_tmp->parent = p;
p->right = r_tmp;
return p;
}
}
int main() {
vector<int> a;
a.push_back(0);
a.push_back(1);
a.push_back(2);
a.push_back(3);
a.push_back(4);
a.push_back(5);
a.push_back(6);
BST_Tree t;
t.root = CreateTree(a, 0, 6);
t.InOrderWalk(t.root);
return 0;
}
非常感谢!
delete parent
。这不是递归调用的正确方式。 - Danparent
是一个非拥有指针。盲目地用智能指针替换每个指针将导致相同的问题(使用unique_ptr<>
)或内存泄漏(使用shared_ptr<>
)。对于父指针使用weak_ptr<>
是过度设计:树不变量(x->left->parent == x
等)保证了parent
始终有效。 - JoergBshared_ptr
,而对于非拥有引用,使用weak_ptr
(或常规指针,如果悬空引用不是问题)。 - Andy Prowl