Recursively freeing C structs

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

    There is no way in the C language to do this, nor would it be desirable - C doesn't know that each member is a distinct pointer allocated via malloc and C contains no run-time type info support to do this - at runtime the compiled code to access the struct is just using offsets off of a base pointer for each member access.

    The simplest approach would be to write a "FreeModel" function:

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

提交回复
热议问题