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;
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);
Is there a way that I can recursively iterate through the pointers in mdl rather than calling free on each element?
(In practice it’s barely any work to just write free() for each one, but it would reduce code duplication and be useful to learn from)
Such functionality is not built in to C, but you can cheat a little bit by abusing the macro preprocessor:
To allocate:
To free:
The nasty bit is that the definition of
struct modeland the definition ofXX_MODEL_POINTERScan become mutually inconsistent, and there’s no way to catch it. For this reason it’s often better to generate the definition ofXX_MODEL_POINTERSby parsing a .h file somewhere.Metaprogramming in C is never easy.