注册 登录
编程论坛 VC++/MFC

用new建立二叉树,不编写内存释放函数严不严重

BYSF_XF 发布于 2011-11-07 21:05, 794 次点击
Tree *create()//前序递归创建二叉树
{
    Tree *head=new Tree;
    char c;
    cin>>c;
    if(c=='#')
        head=NULL;
    else
    {
        head->data=c;
        head->left=create();//创建左子树
        if(head->left==NULL)
            head->l=0;//左子树为空
        head->right=create();//创建右子树
        if(head->right==NULL)
            head->r=0;//右子树为空
    }
    return head;
}
2 回复
#2
yuccn2011-11-08 09:24
就你这个代码 已经出现内存泄露了

if(c=='#')
        head=NULL;
这个地方 head本来是块内存的 ,被你指向null,泄露掉一块内存

应该这样:
char c;
cin>>c;
if(c=='#')
    return NULL;

Tree *head=new Tree;
………………
………………
………………

return head;



#3
Toomj2011-11-08 09:27
那是相当的严重。。。
记住,一个new一个delete,养成好习惯
1