I'm using free() as intended to free the memory occupied by some variable in my case it's struct with more or less following construction:
struct mystruct{
int firstparam;
string secondparam;
struct someOtherSimpleStruct* otherstruct;
the main point is that inside the struct there is other simple (no more nested structs) struct. I just want to make sure that I do understand the way of functioning free() correctly. If I call free with mystruct pointer as an argument the memory will be cleaned just on the first level, so the memory occupied by mystruct = size of int, string and the pointer itself, no other data stored inside someother struct won't be freed and to achieve it the only way is to recursively iterate throughout the whole nested structure? Or maybe there is any universal function which can free a memory of the whole nested structure?
CodePudding user response:
so the memory occupied by mystruct = size of int, string and the pointer itself, no other data stored inside someother struct won't be freed
Correct, because no other data is stored inside the struct. You have a pointer to data stored elsewhere though.
to achieve it the only way is to recursively iterate throughout the whole nested structure?
Yes. Free whatever otherstruct
points at before freeing the surrounding struct, if this is the only pointer referring to that dynamically allocated memory.
Or maybe there is any universal function which can free a memory of the whole nested structure?
No such thing exists.
CodePudding user response:
Since free()
receives a void*
, it has no idea what the allocated space contains or how it is structured. Therefore it cannot release memory recursively.