Recursively freeing C structs

前端 未结 8 638
礼貌的吻别
礼貌的吻别 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:04

    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.

提交回复
热议问题