| Thank you for this, this is helpful. I wrote a JIT compiler and I didn't bother calling free much, I just let the operating system free up all allocated memory. I got into this situation often: return_struct = do_something(mystruct);
return_struct->inner_struct = malloc(sizeof(struct my_inner_struct));
Now, who owns inner_struct? Who is responsible for freeing it? Do I free it when I assign to it?I feel this ownership complicates cross-language FFI API calls, because who is responsible for freeing structures depends on the application and the platform you're running under. For example, Rust code being called from Erlang. You have to be extra careful when memory is managed by a different language runtime. I feel I am at the beginning of intuitively understanding what memory really is: memory is just a huge contiguous region of numbered locations. Bump allocators allocate in one direction and free all at once. Arena allocators allocate to a preallocated region, I think. Memory is a logistical problem of how you arrange and allocate finite resources. I am thinking of alternative visualizations of understanding memory, for example, I started writing an animation of binary search: https://replit.com/@Chronological/ProgrammingRTS The idea is that you see values and memory locations move around with the final goal being able to command memory to move around and be computed, such as real time strategy game. I think if we could visualise memory as cars on a road, we would see obvious traffic jams. |
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.