如何处理错误:双重免费或腐败

how to deal with error:double free or corruption

本文关键字:免费 错误 何处理 处理      更新时间:2023-10-16

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;