←back to thread

237 points ekr____ | 1 comments | | HN request time: 0s | source
Show context
samsquire ◴[] No.42724271[source]
Thanks for such a detailed article.

In my spare time working with C as a hobby I am usually in "vertical mode" which is different to how I would work (carefully) at work, which is just getting things done end-to-end as fast as possible, not careful at every step that we have no memory errors. So I am just trying to get something working end-to-end so I do not actually worry about memory management when writing C. So I let the operating system handle memory freeing. I am trying to get the algorithm working in my hobby time.

And since I wrote everything in Python or Javascript initially, I am usually porting from Python to C.

If I were using Rust, it would force me to be careful in the same way, due to the borrow checker.

I am curious: we have reference counting and we have Profile guided optimisation.

Could "reference counting" be compiled into a debug/profiled build and then detect which regions of time we free things in before or after (there is a happens before relation with dropping out of scopes that reference counting needs to run) to detect where to insert frees? (We Write timing metadata from the RC build, that encapsulates the happens before relationships)

Then we could recompile with a happens-before relation file that has correlations where things should be freed to be safe.

EDIT: Any discussion about those stack diagrams and alignment should include a link to this wikipedia page;

https://en.wikipedia.org/wiki/Data_structure_alignment

replies(4): >>42724597 #>>42724727 #>>42724802 #>>42725393 #
1. caspper69 ◴[] No.42724727[source]
Nothing is going to tell you where to put your free() calls to guarantee memory safety (otherwise Rust wouldn't exist).

There are tools that will tell you they're missing, however. Read up on Valgrind and ASAN.

In C, non-global variables go out of scope when the function they are created in ends. So if you malloc() in a fn, free() at the end.

If you're doing everything with globals in a short-running program, let the OS do it if that suits you (makes me feel dirty).

This whole problem doesn't get crazy until your program gets more complicated. Once you have a lot of pointers among objects with different lifetimes. or you decide to add some concurrency (or parallelism), or when you have a lot of cooks in the kitchen.

In the applications you say you are writing, just ask yourself if you're going to use a variable again. If not, and it is using dynamically-allocated memory, free() it.

Don't psych yourself out, it's just C.

And yes, there are ref-counting libraries for C. But I wouldn't want to write my program twice, once to use the ref-counting library in debug mode and another to use malloc/free in release mode. That sounds exhausting for all but the most trivial programs.