【问题标题】:Assert error when deleting dynamic array nodes from n-ary tree从 n 叉树中删除动态数组节点时断言错误
【发布时间】:2014-03-16 02:11:55
【问题描述】:

我在销毁树时遇到了删除节点的问题。每个节点都是在我的 Tree 类中定义的结构:

struct node
{
    Skill   skill;
    node**  child;

    node(const Skill& aSkill): skill(aSkill)
    {
        child = new node*[CHILD_LIMIT];     // Memory leak happens here
        for(int i = 0; i < CHILD_LIMIT; i++)
            child[i] = NULL;
    }
};

由于每个节点都可以有一定数量的子节点,这些子节点本身就是节点,因此递归对于销毁是有意义的:

Tree::~Tree()
{
    DestroyTree(root); 
}


void Tree::DestroyTree(node*& root)
{
    if(root)
    {
        for(int i = 0; i < CHILD_LIMIT; i++)
            DestroyTree(root->child[i]);    
        delete root;       // Changing this to delete [] root; results in Debug Assertion Failed!
        root = NULL;
    }
}

这段代码有效,但从我的笔记中可以看出;声明指针数组时出现内存泄漏。根据我的发现,这是因为我应该使用

delete [] root;

而不是

delete root;

但这会导致 Debug Assertion Failed 消息与 Expression:_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)。我究竟做错了什么?我看到了很多关于从 n 元树中删除的信息,以及很多关于删除指针数组的信息,但奇怪的是,我很难为这两者的组合找到帮助。

提前致谢!

【问题讨论】:

    标签: c++ recursion memory-leaks tree dynamic-arrays


    【解决方案1】:

    您的数组称为子数组,因此您需要在实际删除节点之前对其调用数组删除。

    void Tree::DestroyTree(node*& root)
    {
        if(root)
        {
            for(int i = 0; i < CHILD_LIMIT; i++)
                DestroyTree(root->child[i]);    
    
            delete [] root->child;
            delete root;
            root = NULL;
        }
    }
    

    【讨论】:

    • 啊!这是有道理的,并解决了断言问题。但是,我在同一点仍然有内存泄漏。
    • @Zeo 您的问题很可能与我们看不到的代码有关。您可以在放置节点的位置发布代码吗?
    • 你是对的!我发现了问题:在声明新节点之前,我没有正确捕获一些不良数据。我将您的回复标记为答案。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 2019-04-11
    • 2019-05-04
    • 1970-01-01
    相关资源
    最近更新 更多