|
|
|
|
|
by heinrichhartman
2119 days ago
|
|
While we are here, does anyone have a good resource about memory management strategies in C? Topics: * Best practices for C function signatures (caller allocates (which size?), callee allocates (where? which allocator?)) * Memory Ownership Models * Borrowing * Reference Counting * Garbage Collectors and C-Libraries providing this functionality * Interning Objects (Strings) * RAII [1]? And it's benefits/flaws [1] https://en.wikipedia.org/wiki/Resource_acquisition_is_initia... Context: I feel that understanding the C memory primitives in not that hard (stack variables, malloc/free, C++'s new). But how to use them is devilishly tricky. I have seen little information about this. |
|
This generally discusses the lack of RAII in C (towards the end), and what to do about it:
https://floooh.github.io/2019/09/27/modern-c-for-cpp-peeps.h...
...and this presents a (reasonably runtime-safe) general memory management strategy using tagged-index-handles instead of pointers:
https://floooh.github.io/2018/06/17/handles-vs-pointers.html
The gist is basically:
- don't allocate small chunks of memory all over the code base, instead move memory management into few centralized systems, and let those systems own all memory they allocate
- don't use pointers as public "object references", instead use "tagged index handles"
- don't use "owning pointers" at all, use pointers only as short-lived "immutable borrow references"