← Back to context

Comment by caspper69

2 days ago

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.