4 ms·
> Now, who owns inner_struct? return_struct does since it is the only thing that knows the address. > Who is responsible for freeing it? return_struct is, un
by secondcoming 3y ago
> Now, who owns inner_struct?
return_struct does since it is the only thing that knows the address.
> Who is responsible for freeing it?
return_struct is, unless you hand that responsibility over to something else.
> Do I free it when I assign to it?
Yes, unless you want leaks.
> I think if we could visualise memory as cars on a road, we would see obvious traffic jams.
That visualisation is helpful for threads, where the program is the road/map and the cars are the threads. I don't see how it's useful for memory.
- jacobsenscott 3y agoA struct can't own something - it isn't a class with a destructor or anything. So it isn't quite so obvious. There are only two lines of code here, but the implication is a function is running that code and then returning `return_struct`, which might get passed around to more functions, and even returned further up the call stack. Somewhere there needs to be code that knows "hey - nobody else is using return_struct, and by the way you need to free return_struct->inner_struct before freeing return_struct.
- secondcoming 3y agoThe implementor of return_struct provides a destroy() function, and because you’re in C land, the programmer knows when to call it.