by rwmj · 1y ago · 0 comments
C programmers are better off with either of these two techniques:
* Use __attribute__((cleanup)). It's available in GCC and Clang, and we hope will be added to the C spec one day. This is widely used by open source software, eg. in systemd.
* Use a pool allocator like Samba's talloc (https://talloc.samba.org/talloc/doc/html/libtalloc__tutorial...) or Apache's APR.
(I didn't include using reference counting, since although that is also widely used, I've seen it cause so many bugs, plus it interacts badly with how modern CPUs work.)
But how did you determine what you could re-use? That's the hard problem, one that's equivalent to calling free() at the right time.
libc already does that. What is it that yours is adding?
I'd say 25 years ago you could write your own naive allocator, make just a couple of assumptions for your use case, and beat libc. But no more.
One of the selling points of Java in the 90s was the compacting part. Because in the 90s fragmentation was a much bigger problem than it is today. Today the libc allocators have advanced by maybe tens of thousands of PhDs worth of theory and practice. Oh, and we have 64bit virtual address space, which helps with some (but not all) of the problems with memory fragmentation.
See this post from Ian Lance Taylor about why Go didn't even bother with a compacting GC: https://groups.google.com/g/golang-nuts/c/KJiyv2mV2pU?pli=1
I mentioned gigabytes because of how mine specifically worked. It allocated chunks in powers of 2, so there was some % of memory that wasn't being used. For instance, If you only need 20 bytes for a string, you got back a pointer for a chunk of 32 bytes. Being just a game, and side project, I never gave it much thought, so I'm curious to hear your input.
defer seems to be making significant progress (having a passionate and motivated advocate in Meneide, and a full TS)
(EDIT: I'm wrong, see reply)
Might have been the previous attempt from years ago, because being block scoped (unlike go) literally has its own section in https://thephd.dev/c2y-the-defer-technical-specification-its...
That is not, as far as I know, how __attribute__((cleanup)) works. It just invokes the callback when the value goes out of scope. So you can't have malloc return an implicitly cleanup'd pointer unless malloc is a macro, in which case you can do the same with a defer block.
Hey, I wrote this GCC plugin to automate reference counting in C. Any bug reports welcome.
Interesting. I'm not very proficient in C, this looks like some sort of finalizers for local variables?
This being C, it's not without its problems. You cannot use it for values that you want to return from the function (as you don't want those to be freed), so any such variables cannot be automatically cleaned up on error paths either. Also there's no automated checking (it's not Rust!)
Note it's {...} scoped, not function scoped, which makes it more useful than Golang's defer.
[1] https://gitlab.com/nbdkit/nbdkit/-/blob/8b36e5a2ea331eed2a73...
I would say this is only half true. With some macro magic you can actually also return the values :)
https://github.com/systemd/systemd/blob/0201114bb7f347015ed4...
To be fair though, you probably meant without any such shenanigans.
if complex_nested_condition {
defer cleanup()
} defer if complex_nested_condition { cleanup() } else { noop() }
In Go, you could do: defer func(run bool) {
if !run { return }
}(condition)
Which admittedly wastes stack space with a noop function in the false case, but whatever.I feel like the number of times I've needed conditional defers is almost zero, while the number of times I've had to make a new function to ensure scoping is correct is huge.
Of especial note, 'mu.Lock(), defer mu.Unlock()' not being scope-based is the largest source of deadlocks in code. People don't use 'defer' because the scoping rules are wrong, code panics before the manual unlock call, and then the program is deadlocked forever.
It’s odd that the suggestion for a feature lacking in C is to use a non standard but well used supported path. c’s main selling point (IMO) is that it _is_ a standard, and relying on compiler vendor extensions kind of defeats the purpose of that.
Well, yeah...
How do you think Annex K got in?
Let's be honest, how many compilers are available, and how many of those would you actually use?
The answer isn't more than 4 and the 2 compilers you are most likely to use among those already support this and probably won't stop supporting without a good alternative.
I like standardisation, but you have to be realistic when it helps you without a large real cost other than fighting your ideals for getting this into the standard first.
The libraries you listed are all full of platform-specific code, and also have plenty of compiler-specific code behind ifdefs (for instance the stb headers have MSVC specific declspec declarations in them).
E.g. there is hardly any real-world C code out there that is 'pure standard C', if the code compiles on different compilers and for different target platforms then that's because the code specifically supports those compilers and target platforms.
I'd target the latest C standard and won't even care to know how many old, niche compilers I'm leaving out. These are vastly different uses for C and obviously your gaols drastically change your standard or compiler targeted.
But then again you are probably not doing a whole lot of heap management in embedded code.
Call it a posix extension, fair enough. But if your reason for writing C is that it’s portable, don’t go relying on non portable vendor specific extensions.
It's the same thing with the web and browser vendors, there's a constant mismatch, browsers propose and implement things and they may get standardized, and the standard dictates new requirements which might get implemented by all vendors.
The point of standardisation is defining behaviour for the things that are implemented as exploratory improvements and should be implemented on the more conservative compilers.
It's your choice whether to target the standard or a few selected compilers, there's a cost for both options between being late to improvements vs the possibility of needing to revisit your code around each of the "extensions" you decided to depend on.
If in certain projects portability is somehow of upmost importance, then any discussion around looking through the standard's black box to reach out for new stuff is kind of useless.
[0] https://thephd.dev/c2y-the-defer-technical-specification-its...
[1] https://thephd.dev/_vendor/future_cxx/technical%20specificat...
The *actual* power and flexibility of C lies in the non-standard, vendor-specific language extensions.
Really, don’t do this, it’s a portability nightmare. If you’re going to write C stick to code that easy to run under MSVC.
mingw is radically more problematic than MSVC. Don’t use mingw.
Can you expand on this?
In reality, your milage will heavily vary. If you don't have contention (you don't commonly share objects across multiple threads concurrently), it's likely that reference counting will perform very well. Whether this is the common case really depends on the kinds of software you write.
I've seen this happen in cases arrays of objects are allocated, ie one per thread, and then handed to a thread pool to work on.
Even if heap allocated, if the object is just a reference counter and a few pointers, the memory allocator can fit several of them next to each other causing them to share cache lines, which causes the performance issues with atomic operations.
Depends on implementation of things of course, but can be a pitfall.
The "tl;dr" summary is that `free_on_exit()` replaces the caller's return address with a trampoline that calls a `do_exit()` function that frees all the memory marked to be freed "on exit", and it uses its own stack of cleanup handler closures so-to-speak. When returning all the allocations are freed and then the original return address is returned to.