r/C_Programming • u/gargamel1497 • Aug 11 '26
Discussion Easening memory management by simply declaring ownership?
After a half-year-long Java project I'm writing something in C and the lack of a garbage collector can be positively felt in terms of performance but at the same time managing all the pointers can get messy.
There's a whole nother language decidated to solve this problem (while creating a thousand more), but there's got to be a simpler solution.
And yesterday I thought, why not just mark the ownership of the various pointers I've got in my project?
By ownership I of course mean which struct (I do use OOP, sorry) is responsible for freeing that pointer.
And I #define'd three constants.
The MANAGED constant means the struct that contains the pointer has to free it.
The FOREIGN constant means that it's somebody else's job.
The SHARED constant means that it ought to be someone else's job, but it may not be freed when the program exists and should thus be freed.
I place them before the whole declaration in this manner:
MANAGED FONT *fontGothic;
SHARED struct WORLD *currentWorld;
FOREIGN struct PERSON *thePlayer;
This doesn't mean anything to the compiler, but it's just a quick way of telling me what is what.
It is definitely a very stupid idea and I apologize for posting it. I'm just a silly dude who does silly things.
7
u/aocregacc Aug 11 '26
If there's no tool that can read it it's the same as a comment. Generally it's probably a good idea to document the ownership of your pointers, and if you prefer this over a regular comment, why not.
4
u/mlugo02 Aug 11 '26
I would just look into memory arenas. Pre allocated memory as much as possible and reuse it instead of allocating and freeing all over your code base
64
u/smtp_pro Aug 11 '26
When I write C, I try to not manage memory at all. The caller has all ownership.
I rarely have functions perform allocations. I make the caller allocate the memory and pass my functions the pointers.
3
u/runningOverA Aug 11 '26
Things will get complex after a while, as your project grows.
Use a fat pointer and ref_counting atop this.
26
u/flyingron Aug 11 '26
Garbage collection can cause significant performance issues. This is why C doesn't do that.
A better philosophy is to make things symetrical when ever possible. If the caller allocates memory, the caller deallocates it. If the called function allocates something, there should be a matching function to clean it up.
2
u/Big-Rub9545 Aug 11 '26
It won't solve the memory management problems (you still have to handle that memory yourself), but as a sort-of documentation tool, I quite like it.
3
u/Beginning-Junket8979 Aug 11 '26
If your code's memory management is complex enough that you need this and you have the option to use C++, it might be worth it even if only for
<memory>smart pointers.That out of the way...
If sticking you're sticking with pure C -- yeah it's not a terrible convention but not especially useful other than as a documentation convention.
Ref counting is the simplest solution that actually does something meaningful at runtime.
Take a peek at some scripting/interpreted language internals (eg CPython, Lua) for examples.
You might also be interested in cleanup attributes...
https://hackerbikepacker.com/kernel-auto-cleanup-1
...Which is the closest you can get to having real destructors in C.
2
u/CowBoyDanIndie Aug 11 '26
Thats basically what we do in modern C++ with unique_ptr, though most of the time the stl containers take care of it for us
1
u/faculty_for_failure Aug 11 '26
I usually just pass in temp or perm arenas or slabs. Avoid many small heap allocations, perform fewer but larger ones.
1
u/flatfinger Aug 12 '26
It irks me that more languages don't more clearly incorporate object ownership into the type system. Upholding an invariant that specifies that all pointers an object owns will either identify a live object or be null outside of a very narrow interval between allocating storage and zero-initializing it, and that the only times an object may own another object without having a reference stored are within specific patterns that create a sub-object and immediately store a reference, or copy a reference to a temporary, erase the reference, and then delete the object identified by the temporary, will make it very easy to avoid memory leaks as well as use-after-free and double-free scenarios.
1
u/Zirias_FreeBSD Aug 13 '26
Clearly defining ownership is IMHO the most important thing to do to avoid memory management errors in more complex scenarios.
Your documentation scheme looks helpful to achieve that. I personally prefer a simpler approach based on const-ness, which IMHO works well with an OOP model: Ownership of an object means having a non-const pointer to it (as returned by a constructor-like function). This has a few implications for your model, as your objects should be useful in an immutable state, and you must also think about lifecycles (storing a const pointer can be dangerous, it could silently become dangling when stored for longer than the lifecycle of the actual owner). But in my experience, it applies quite well to many real-life scenarios.
One somewhat common issue with that approach is the occasional need for objects that can't have a dedicated owner, but are naturally "shared" instead. The very simple solution of reference counting helps with these, which can be elegantly hidden in your constructor- and destructor-like functions. In this case, multiple other modules might obtain and store a non-const pointer by calling a "referencing" function (internally incrementing the counter) and are then obliged to also call the destructor-like function when they are done with the object. This would only do actual destruction once decrementing the internal counter reaches zero again. But be warned this needs synchronization / mutual exclusion as soon as you need it in a multi-threaded environment.
1
u/NoSpite4410 Aug 14 '26
It is actually simple - -if you use malloc, calloc, or realloc, you write a free command for it.
While you are writing malloc code, you are already thinking about where and when to free it.
Also, freeing it may not be really all that necessary. The program might end and so everything gets cleaned up then. Rarely will stuff blow up the program, unless it uses lots of memory and runs for a long time.
If you are writing servers, yes very important, no leaks. One shot jobs, not so much.
A game has a relatively long running time, lots of dynamically allocated things. A memory pool is usually a good
idea, or even linked lists than can be periodically cleaned up.
1
u/TituxDev Aug 16 '26
I did a mem managemer system for a proyect. Not the best solution but works fine You can find it in the file ntmemory.c in my repo https://github.com/TituxDev/NeuroTIC
1
u/LordRybec Aug 16 '26
There are a lot of ways for handling memory safely in C, without costing extra resources. Like many others, my default strategy is to avoid ever allocating memory within functions that isn't freed before the function returns. Overall this is a good default strategy, but it doesn't always meet my needs. What strategy I use at that point depends largely on how frequently my default strategy is violated. If it's just once, that's easy to keep track of. Maybe leave a paper trail of comments following the memory. Otherwise more elaborate strategies may be necessary.
What I'd love to see (and might make myself, if I ever have time) is a pragma language and linter rules for tracking heap memory and flagging unsafe use. Ideally this would work similarly to Rust's memory safety, except you would use pragmas to tell the linter which heap allocations it should impose safety rules on. Pragmas would also be used to track ownership of memory flagged as tracked. Obviously the compiler wouldn't care, and that's part of the point (I hate languages that add artificial restrictions in the name of safety), but the linter would flag safety violations on an opt-in basis. This would make memory safety in C much easier without getting in the way of more complex or unusual use cases.
Anyhow, it's not stupid if it works and doesn't come at an excessive cost. (Some have mentioned that it could confuse other people, and that's true, but that's only a cost if other people need to work on or maintain the cost, and even then it may not be excessive if they can learn what's going on easily.)
1
u/ern0plus4 Aug 11 '26
Take a look on Rust, it shows the way.