gpt4 book ai didi

C++ 错误 : Pointer being freed was not allocated

转载 作者:行者123 更新时间:2023-11-28 00:55:18 24 4
gpt4 key购买 nike

我正在构建一个 AVL 树。我有一种方法可以删除树中的项目,但出现错误。

这是我得到的运行时错误:

malloc: *** error for object 0x100100120: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
jim Abort trap

我的类(class)是这样的:

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 ) ;
}

为什么会出现此错误?

最佳答案

tl;dr 但是 - 类管理内存 + 内存管理错误 ->

您正在实现一个析构函数,这意味着您的复制/销毁逻辑比浅拷贝可以处理的更多。这是有道理的,因为您有一个成员 Avlnode *root;

要么使用 RAII,要么正确实现复制构造函数和赋值运算符。

这被称为三法则。使用的所有术语都可以轻松谷歌搜索。

关于C++ 错误 : Pointer being freed was not allocated,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11812999/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com