【发布时间】: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