递归释放C结构 [英] Recursively freeing C structs

查看:196
本文介绍了递归释放C结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个只包含内存指针,我已经分配的结构。有没有一种方法可以递归自由每个是一个指针,而不是调用free每一个?

I have a struct that only contains pointers to memory that I've allocated. Is there a way to recursively free each element that is a pointer rather than calling free on each one?

例如,假设我有这样的布局:

For example, let's say I have this layout:

typedef struct { ... } vertex;
typedef struct { ... } normal;
typedef struct { ... } texture_coord;

typedef struct
{
    vertex* vertices;
    normal* normals;
    texture_coord* uv_coords;
    int* quads;
    int* triangles;
} model;

在我的code我的malloc每个结构来创建一个模型:

And in my code I malloc each of the structs to create a model:

model* mdl = malloc (...);
mdl->vertices = malloc (...);
mdl->normals = malloc (...);
mdl->uv_coords = malloc (...);
mdl->quads = malloc (...);
mdl->triangles = malloc (...);

这是简单的释放每个指针像这样:

It's straightforward to free each pointer as so:

free (mdl->vertices);
free (mdl->normals);
free (mdl->uv_coords);
free (mdl->quads);
free (mdl->triangles);
free (mdl);

有没有办法,我可以通过MDL指针递归迭代,而不是调用free每个元素的方法吗?

Is there a way that I can recursively iterate through the pointers in mdl rather than calling free on each element?

在实践中它几乎没有任何工作,只写免费的()为每一个,但它会降低code重复,并从学习有用的)

推荐答案

这样的功能并不内置于C,但是你可以通过滥用宏观preprocessor骗一点:

Such functionality is not built in to C, but you can cheat a little bit by abusing the macro preprocessor:

#define XX_MODEL_POINTERS do { \
  xx(vertices); xx(normals); xx(uv_coords); xx(quads); xx(triangles); \
} while(0)

要分配:

model *mdl = malloc(sizeof(*mdl));
assert(mdl);
#define xx(N) mdl->N = malloc(sizeof(*mdl->N)); assert(mdl->N)
XX_MODEL_POINTERS;
#undef xx

要释放:

assert(mdl);
#define xx(N) free(mdl->N); mdl->NULL
XX_MODEL_POINTERS;
#undef xx
free(mdl);
mdl = NULL;

讨厌的一点是,结构模型和定义的定义 XX_MODEL_POINTERS 可以成为相互不一致,和有没有办法抓住它。基于这个原因,通常最好由地方解析.h文件中生成 XX_MODEL_POINTERS 的定义。

The nasty bit is that the definition of struct model and the definition of XX_MODEL_POINTERS can become mutually inconsistent, and there's no way to catch it. For this reason it's often better to generate the definition of XX_MODEL_POINTERS by parsing a .h file somewhere.

在元编程C是不容易的。

Metaprogramming in C is never easy.

这篇关于递归释放C结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆