Recursively freeing C structs

前端 未结 8 696
礼貌的吻别
礼貌的吻别 2020-12-31 23:23

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

8条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-01 00:02

    Take a look at talloc http://talloc.samba.org/ if you do:

    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, ...);
    

    you can then:

    talloc_free(mdl);
    

    and talloc will take care of free'ing all the other blocks you called talloc with mdl as the first argument at allocation time (and it will do this recursively you can do talloc(mdl->vertices, ...) and talloc_free(mdl); will get that too)

    as an aside there is a slight overhead to using talloc because it needs to track what stuff recurse over, but it's not very much.

提交回复
热议问题