你怎么能用 POSIX 个函数清理整个 POSIX 树?

How can you clean an entire POSIX tree with only POSIX functions?

tsearch 填充了 POSIX 二叉树,如何清理整棵树? GCC 提供 tdestroy 作为扩展,但是如果你想使用 POSIX-only 函数你怎么能做到呢?

我当前的实现使用 twalk 来遍历树,并且对于 endorderleaf 节点,调用 tdelete,但这可以理解地显示关于 const-correctness 的警告:

static void free_tree(const void *node, const VISIT which, const int depth)
{
        struct search_entry *entry;
        switch (which) {
                case endorder:
                case leaf:
                        entry = *(struct search_entry **)node;
                        tdelete(entry->key, &node, search_entry_compare);
                        free(entry);
        }
}

POSIX 兼容应用程序的预期方法是什么?

建议的从 twalk()action 调用 tdelete() 的解决方案与应用程序 action 和 [=14] 的 POSIX 要求冲突=] 不改变树。实际上,可能会在免费或不完全清理后使用。

我能想到的最好的办法是不使用 tsearch/tfind/tdelete/twalk 或分配新内存来存储 twalk() 结果,然后再使用 tdelete()

不使用 tsearch/tfind/tdelete/twalk 也可能允许基数尝试和哈希表等数据结构在现代体系结构上往往比二叉树更有效。

tsearch() 系列函数的 POSIX 描述有一个信息丰富的 Examples 部分,它显示了标准认为您可以删除所有元素的方式一棵树(作为更大、更完整的函数使用示例的一部分):

/* Delete all nodes in the tree */
while (root != NULL) {
    elementptr = *(struct element **)root;
    printf("deleting node: string = %s,  count = %d\n",
           elementptr->string,
           elementptr->count);
    tdelete((void *)elementptr, &root, delete_root);
    free(elementptr);
}

基本上就是反复删除tdelete()的根节点,直到没有根节点可以删除为止。还显示了 delete_root() 函数——它是一个空操作,returns 0 表示成功。

我们可以在 tdelete().

的通话中讨论演员的优点(或缺点)