释放trie上的指针

Deallocate pointer on trie

本文关键字:指针 trie 释放      更新时间:2023-10-16

我试图在我的树上释放指针。这是我的结构体

struct trie
{
    int x;
    trie *next[26];
};
trie *head;
trie *tmp;
下面是使用dfs 的deallocate函数
void deallocate(trie *cur)
{
    for (int a=0; a<=25; a++)
    {
        if (cur->next[a] != NULL)
        {
            tmp = cur->next[a];
            cur->next[a] = NULL;
            deallocate(tmp);
        }
    }
    free(cur);
}

这是head init函数

void init()
{
    head = new trie;
    head->x = 0;
    for (int a=0; a<=25; a++)
    {
        head->next[a] = NULL;
    }
}

,程序结束后我叫它deallocate(head);

我真的是新的指针的东西,我的deallocate函数有什么问题吗?由于

改变数组大小并被接受:)似乎问题不是指针:)谢谢大家

您使用new来分配内存,使用free来释放内存。我能看到的唯一错误是,您应该使用newdelete,或mallocfree

您的函数对于空输入是不正确的。deallocate(NULL)将崩溃。函数(尤其是构成框架的一般函数)应该是自给自足的,并且应该能够覆盖所有可能的输入。

  • deallocate需要处理NULL输入

    if (cur == NULL){返回;}

    功能开始

  • *head应该在声明

    时声明为NULL