Recursively freeing C structs

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

    You could calculate the size needed for all of them together and do one big malloc

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

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

    Then to free it is just one free.

    You may have to worry about alignment issues (depending on your platform) but that shouldn't be too tough to figure out. The other problem is that it is a much larger chunk which may present a problem if in a memory constrained environment.

提交回复
热议问题