Question

I'm having an issue with deleting nodes when destroying a tree. Each node is a struct defined in my Tree class:

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). 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.

Thanks in advance!

Était-ce utile?

La solution

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;
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top