实现n-ary树的析构函数

时间:2013-12-30 11:47:26

标签: c++ tree destructor

我一直在处理n-ary树。那么现在我需要为它编写销毁部分。我所做的是创建一个全局堆栈和一个辅助函数。想法是程序完成后,将调用析构函数。在析构函数中,我调用了我的辅助函数,其中我的帮助函数将所有要删除的节点放在堆栈中。后来我逐个删除存储在堆栈中的节点。

问题是当我运行valgrind来检查释放的内存时,它会产生一些被抑制的错误,似乎并非所有树都被删除了。

Node* destroy_des(Node* ptr)
{
    if(ptr == NULL)
        return NULL;
    else 
       des.push(ptr);

    for(Node *pChild=ptr->getFirstChild(); pChild!=NULL;  pChild=pChild->getNextSibling())
    {
         Node *pTarget = destroy_des(pChild);
    }
    return NULL;
}

这里堆栈的名称是'des',在helper函数中root被作为参数传递

TREE :: ~TREE()
 {
    destroy_des(root);   

   while( !des.empty())
   {    
        Node* temp = des.top();
        des.pop();
        temp->setNextSibling(NULL);
        temp->setParent(NULL);
        temp->setFirstChild(NULL);
        delete temp;
   }
} 

修改

 ==26349== Conditional jump or move depends on uninitialised value(s)
 ==26349==    at 0x40348B: destroy_des(Node*) (in /Desktop/hw3/a.out)
 ==26349==    by 0x40346C: destroy_des(Node*) (in /Desktop/hw3/a.out)
 ==26349==    by 0x40346C: destroy_des(Node*) (in /Desktop/hw3/a.out)
 ==26349==    by 0x414EED: TREE::~TREE() (in        /home/bs04/e1848357/Desktop/hw3/a.out)
 ==26349==    by 0x414FD4: main (in /home/bs04/e1848357/Desktop/hw3/a.out)
 ==26349== 
 ==26349== Conditional jump or move depends on uninitialised value(s)
 ==26349==    at 0x40348B: destroy_des(Node*) (in /Desktop/hw3/a.out)
 ==26349==    by 0x40346C: destroy_des(Node*) (in /Desktop/hw3/a.out)
 ==26349==    by 0x414EED: TREE::~TREE() (in /Desktop/hw3/a.out)
 ==26349==    by 0x414FD4: main (in Desktop/hw3/a.out)
 ==26349== 
 ==26349== Conditional jump or move depends on uninitialised value(s)
 ==26349==    at 0x40348B: destroy_des(Node*) (in /Desktop/hw3/a.out)
 ==26349==    by 0x414EED: TREE::~TREE() (in /Desktop/hw3/a.out)
 ==26349==    by 0x414FD4: main (in /Desktop/hw3/a.out)
 ==26349== 
 ==26349== 
 ==26349== HEAP SUMMARY:
 ==26349==     in use at exit: 165 bytes in 10 blocks
 ==26349==   total heap usage: 716 allocs, 706 frees, 46,064 bytes allocated
 ==26349== 
 ==26349== LEAK SUMMARY:
 ==26349==    definitely lost: 55 bytes in 6 blocks
 ==26349==    indirectly lost: 110 bytes in 4 blocks
 ==26349==      possibly lost: 0 bytes in 0 blocks
 ==26349==    still reachable: 0 bytes in 0 blocks
 ==26349==         suppressed: 0 bytes in 0 blocks
 ==26349== Rerun with --leak-check=full to see details of leaked memory
 ==26349== 
 ==26349== For counts of detected and suppressed errors, rerun with: -v
 ==26349== Use --track-origins=yes to see where uninitialised values come from
 ==26349== ERROR SUMMARY: 3 errors from 3 contexts (suppressed: 4 from 4)

0 个答案:

没有答案