FR version is available. Content is displayed in original English for accuracy.
Advertisement
Advertisement
⚡ Community Insights
Discussion Sentiment
67% Positive
Analyzed from 685 words in the discussion.
Trending Topics
#safer#real#apis#type#integer#library#clang#bounds#safety#both

Discussion (17 Comments)Read Original on HackerNews
Various patterns for safer C programming have been cargo-culting around the industry for decades. Because the language evolves intentionally slowly, these patterns rarely get folded into the language as first-class constructs and are passed down through the generations in a sort of oral tradition of programming.
lib0xc leverages GNUC extensions and C11 features to codify safer C practices and patterns into real APIs with real documentation and real testing. Reduce your casts to and from `void *` with the `context_t` tagged pointer type. Enable type-checked, deferred function invocation with `call_t`. Interrogate structure descriptors with `struct_field_t`. Stop ignoring `-Wint-conversion` and praying you won't regret it when you assign a signed integer to an unsigned integer and use `__cast_signed_unsigned`. These are just a few of lib0xc's standard-library-adjacent offerings.
lib0xc also provides a basic systems programming toolkit that includes logging, unit tests, a buffer object designed to deal with types, a unified Mach-O and ELF linker set, and more.
Everything in lib0xc works with clang's bounds-safety extensions if they are enabled. Both gcc and clang are supported. Porting to another environment is a relatively trivial effort.
It's not Rust, and it's not type safety, but it's not supposed to be. It's supposed to help you make your existing C codebase significantly safer than it was yesterday.
My employer holds the copyright and has permitted its release under the MIT license.
What do you think C would need in order to reach the user experience of those languages?
The C committee at least seems to get it now. The C++ committee still doesn't, led in large part by Bjarne.
If you get compiler errors, it means you were printing to a heap-allocated buffer (or a buffer whose bounds you did not know), and you should be propagating bounds and using `snprintf`.
Integer conversion is the same way. If you have something like
int v1; uint64_t v2;
<stuff happens>
v2 = (uint64_t)v1;
Then you can replace it with
v2 = __cast_signed_unsigned(uint64_t, v1);
and you'll get a runtime trap when v1 is a negative value, meaning you can both enable -Wint-conversion and have defined behavior for when the value in a certain integer type is not representable in another.