Recursive release of C-structures

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)

+3
source share
8

C, , :

#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;

, struct model XX_MODEL_POINTERS , . XX_MODEL_POINTERS .h.

C .

+6

- , , .

void freeModel( model* md1 ) {
    free (mdl->vertices);
    free (mdl->normals);
    free (mdl->uv_coords);
    free (mdl->quads);
    free (mdl->triangles);
    free (mdl);
}
+18

C , - C , , malloc, C - .

- "FreeModel":

void FreeModel(model* mdl)
{
   free(mdl->vertices);
   ... // Other frees
   free(mdl);
}
+7

, , malloc

sizeof (model) + sizeof (vertex) * nVertices... ..

mdl, result + sizeof (model) model- > vertices...

, , .

, ( ), . , , , .

+3

talloc http://talloc.samba.org/, :

model* mdl = talloc (NULL, ...);
mdl->vertices = talloc (mdl, ...);
mdl->normals = talloc (mdl, ...);
mdl->uv_coords = talloc (mdl, ...);
mdl->quads = talloc (mdl, ...);
mdl->triangles = talloc (mdl, ...);

:

talloc_free(mdl);

talloc free , talloc, mdl ( , talloc(mdl->vertices, ...) talloc_free(mdl); )

talloc, , , .

+3

?

+2

, C.

, .

EDIT: Ups, , ...

0

Not with these structures. You can add another entry to the top-level model structure containing a list of pointers to be freed and repeat this list. But I doubt that such complexity and clarity of this decision will be worth it. (Unless you have a much larger and more deeply nested set of records available in the top-level model structure than you show here.)

0
source

Source: https://habr.com/ru/post/1709639/


All Articles