简体   繁体   English

从n元树中删除动态数组节点时断言错误

[英]Assert error when deleting dynamic array nodes from n-ary tree

I'm having an issue with deleting nodes when destroying a tree. 我在销毁树时删除节点时遇到问题。 Each node is a struct defined in my Tree class: 每个节点都是在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;
    }
};

Since each node can have some number of children which are nodes themselves, a recursion makes sense for destruction: 由于每个节点可以具有一定数量的子节点,而这些子节点本身就是节点,因此进行递归销毁很有意义:

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

This code functions, but as you can see from my notes; 该代码起作用,但是正如您从我的笔记中看到的那样; I've got memory leak when declaring the pointer array. 声明指针数组时发生内存泄漏。 From what I've found, it's because I should be using 根据我的发现,这是因为我应该使用

delete [] root;

instead of 代替

delete root;

but that's resulting in a Debug Assertion Failed message with Expression:_BLOCK_TYPE_IS_VALID(pHead->nBlockUse). 但这会导致一条带有以下表达式的调试断言失败消息:_BLOCK_TYPE_IS_VALID(pHead-> nBlockUse)。 What am I doing wrong? 我究竟做错了什么? I'm seeing plenty of information about deleting from n-ary trees, and plenty about deleting pointer arrays, but struggling to find help for the combination of the two, oddly. 我看到了大量有关从n元树中删除的信息,以及有关删除指针数组的大量信息,但是奇怪的是,我一直在努力寻求二者结合的帮助。

Thanks in advance! 提前致谢!

Your array is called child, so you need to call array delete on this before actually deleting the node. 您的数组称为子数组,因此需要在实际删除节点之前对此调用数组删除。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM