0
我正在構建AVL樹。我有一個方法來刪除樹中的項目,但是我收到一個錯誤。C++錯誤:正在釋放的指針未分配
這是運行時錯誤,我得到:
malloc: *** error for object 0x100100120: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
jim Abort trap
我的類看起來是這樣的:
struct Avlnode{
string data;
int balfact;
Avlnode *left;
Avlnode *right;
};
class Avltree{
public:
Avltree();
~Avltree();
Avlnode* insert(string i, bool* j);
static Avlnode* buildtree (Avlnode *root, string data, bool *h) ;
void display(Avlnode *root);
Avlnode* deldata (Avlnode* root, string data, bool *h);
static Avlnode* del (Avlnode *node, Avlnode* root, bool *h);
static Avlnode* balright (Avlnode *root, bool *h);
static Avlnode* balleft (Avlnode* root, bool *h);
void setroot (Avlnode *avl);
static void deltree (Avlnode *root);
private:
Avlnode *root;
int items;
};
和deldata的定義是這樣的:
Avlnode* Avltree::deldata (Avlnode *root, string data, bool *h){
Avlnode *node;
if (root == NULL){
//cout << "\nNo such data.";
return (root);
}
else{
if (data < root -> data){
root -> left = deldata (root -> left, data, h) ;
if (*h)
root = balright (root, h) ;
}
else{
if (data > root -> data){
root -> right = deldata (root -> right, data, h) ;
if (*h)
root = balleft (root, h);
}
else{
node = root;
if (node -> right == NULL){
root = node -> left ;
*h = true ;
delete (node) ;
}
else{
if (node -> left == NULL){
root = node -> right ;
*h = true ;
delete (node) ;
}
else{
node -> right = del (node -> right, node, h) ;
if (*h)
root = balleft (root, h) ;
}
}
}
}
}
return (root) ;
}
Avlnode* Avltree :: del (Avlnode *succ, Avlnode *node, bool *h){
Avlnode *temp = succ ;
if (succ -> left != NULL){
succ -> left = del (succ -> left, node, h) ;
if (*h)
succ = balright (succ, h) ;
}
else{
temp = succ ;
node -> data = succ -> data ;
succ = succ -> right ;
delete (temp) ;
*h = true ;
}
return (succ) ;
}
爲什麼我得到這個錯誤?
當我有數據爲int時,它正在工作。不知道這是否與它有什麼關係...... – Jordan 2012-08-05 00:23:17