I have a structure that contains only the pointers to memory that I allocated. Is there a way to recursively free each element that is a pointer, rather than calling free on each of them?
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 structures to create the model:
model* mdl = malloc (...);
mdl->vertices = malloc (...);
mdl->normals = malloc (...);
mdl->uv_coords = malloc (...);
mdl->quads = malloc (...);
mdl->triangles = malloc (...);
Directly free each pointer like this:
free (mdl->vertices);
free (mdl->normals);
free (mdl->uv_coords);
free (mdl->quads);
free (mdl->triangles);
free (mdl);
Is there a way by which I can recursively iterate over pointers in mdl and not call it for free for each element?
(In practice, it's hardly any work to just write free () for each of them, but that would reduce code duplication and be useful to learn)
source
share