当前位置:  开发笔记 > 编程语言 > 正文

Destruction of structures (freeing memory)

如何解决《Destructionofstructures(freeingmemory)》经验,为你挑选了1个好方法。

Whenever you write a destructor for a user defined structure, do you try to dive into the structure and free as much as possible, or do you instead just free the structure itself and expect the caller to be careful about memory leaks.

I can think of pros and cons to both approaches. Is there a standard community accepted way of writing destructor?

Toy Example

struct node {
    int *ptr;
    int num;
}
void node_free(struct node *n) {
    /* Would you include this? */
    if (n->ptr != NULL) free(n->ptr);
    free(n);
}

Scenario that raised the question

In a graph algorithm, I want to be able to insert vertex structures into several lists at once. I created a wrapper structure that points to a vertex, and I can then insert these wrapper structures into lists. When I construct the wrapper, I pass a pointer to a vertex structure. When I destruct the wrapper, I can't destruct the vertex structure as well. So that's the scenario that made me ask this question: Is there a standard approach to writing destructors that allos the programmer not to worry about these details?



1> Ki Jéy..:

拥有用于自定义结构的自定义析构函数的主要兴趣在于:确保同时释放结构的每个分配部分。应该将struct用户分配并开始使用它,然后在不再使用它时销毁它。

答案很简短:是的

推荐阅读
夏晶阳--艺术
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有