如何处理错误:双重免费或腐败
how to deal with error:double free or corruption
update: removeNode代码修订。没有错误,可以运行,但没有输出。输出应该是在main函数中简单地打印出向量。我现在还在检查bug。非常感谢你的帮助。如果有人发现任何问题,请告诉我。非常感谢。
=======================
得到的错误是*** glibc detected *** ./bintree: double free or corruption (fasttop): 0x0000000000727060 ***
程序很简单,执行以下步骤:
- 求二叉树的最小值;
- 在矢量中记录最小值;
- 删除树中值最小的节点;
- 重复1-3,直到树为空。
树定义如下,语言为c++
typedef struct myNode* LPNode;
typedef struct myNode Node;
struct myNode
{
double key;
LPNode Left; //left subtree
LPNode Right; //right subtree
};
这是一个简单的删除节点函数,因为每次都会删除最小的值。节点有点像叶节点,所以没那么复杂。compareDouble(双a,双b)将返回true
如果a < b
;false
if a > b
//delete a node
void removeNode(LPNode Root,double min)
{
if(compareDouble(min,Root->key)) {
if(Root->Left != NULL)
removeNode(Root->Left,min);
else
printf("Remove bug!n");
}else{
//delete Root;
//Root=Root->Right;
LPNode tmp = MakeNewNode(Root->key);
tmp->Left = Root->Left;
tmp->Right = Root->Right;
delete Root;
Root=tmp->Right;
}
}
nmax初始化为0,sortevector被分配一个空间与树中总节点一样大的向量,min初始化为99999。minValue将返回树的最小值。
//call minValue to find the min key
//record the min key in a vector
//call removeNode to delete the Node
//repeat till the tree is empty
void problem1(LPNode Root,double* sortedvector,int& nmax)
{
double min = MAX;
while(Root!=NULL)
{
sortedvector[nmax] = minValue(Root,min) ;
nmax++;
removeNode(Root,min);
}
printf("The tree is empty");
}
对节点使用std::unique_ptr
s比使用LPNode
s要好得多。然后你甚至不需要做任何delete
,更不用说追踪由于它们而产生的bug了。你的错误之一是使用Root
后,你已经delete
d它:
delete Root;
Root=Root->Right;
你需要更像:
NewRoot = Root->Right;
delete Root;
Root = NewRoot;
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 全球免费给出一个错误.调试器不解释
- 使用线程和静音时,双免费或损坏(!prev)错误
- TBB免费图像lambda阵列比较错误
- 使用数组作为参数时,免费出现c++错误
- 范围末尾的C 双免费或损坏错误
- C 双免费或损坏错误
- 最Vexing的朋友?朋友化一个专门的免费函数模板会引发编译错误(当重载一个方法时)
- 使用boost.asio的免费async_*函数时出现奇怪的错误
- AddressSanitizer GCC 4.8的双重免费错误
- 如何处理错误:双重免费或腐败
- 共享所有权双重免费错误
- 双重免费或腐败错误- valgrind