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 eac
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)
To allocate:
model *mdl = malloc(sizeof(*mdl));
assert(mdl);
#define xx(N) mdl->N = malloc(sizeof(*mdl->N)); assert(mdl->N)
XX_MODEL_POINTERS;
#undef xx
To free:
assert(mdl);
#define xx(N) free(mdl->N); mdl->NULL
XX_MODEL_POINTERS;
#undef xx
free(mdl);
mdl = NULL;
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.
Metaprogramming in C is never easy.