122 points · by signa11 · 3y ago · 86 comments
Hello, hi! I'm Oleksandr Kaleniuk, and I wrote the thing back in 2020. Please don't take it all too seriously. There was COVID-19, I had nothing better to do.
I did write a new book since then, and my publisher would bite my head off for missing this opportunity. It's called Geometry for Programmers and it was published by Manning just this year. https://www.manning.com/books/geometry-for-programmers It's about curves, surfaces, transformations, homogeneous coordinates, rational splines, distance fields, and voxels. You don't have to know any advanced math to enjoy the book, but you might want to know a bit of Python. It's for programmers, so the didactic tools there are mostly code, not theorems.
This is 10 blog posts in one PDF, and each post is good.
sizeof(*(&s))
I mean, wut? Really?? This should just be sizeof s
Since sizeof is not a function, and redirecting by dereferencing a pointer that is just created by taking the address of a local is silly.Not overly impressed by this.
> But "sizeof()" really is a function. It acts exactly like a function of it's argument. There is no reason to not treat it that way.
That's just how it is, and really what's wrong with it? We're not in lisp after all. Let's not pretend it's a function, because otherwise an expression like
sizeof(obj).member
would be at least confusing.It used to be compile-time only until C99, which allowed it to be applied to a variable-length array (VLA). Thus it potentially has run-time semantics, though still not a function. Address-of (&) has run-time semantics, since the address of an object is rarely constant, and isn't a function either.
If it acts exactly like a function, show me its prototype, and how you would call it through a function pointer. I'll be here, waiting while thumbing through my old K&R, or something ...
Also, when using variable-length arrays (which are being phased out, but they are in for instance C99) this works:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
size_t arglens[argc];
for (size_t i = 0; i < sizeof arglens / sizeof *arglens; ++i) {
arglens[i] = strlen(argv[i]);
}
printf("Computed %zu lens:\n", sizeof arglens / sizeof *arglens);
for (size_t i = 0; i < sizeof arglens / sizeof *arglens; ++i) {
printf("%zu: '%s' is %zu\n", i, argv[i], arglens[i]);
}
return 0;
}
Compile (as C99!) and run: $ gcc -o arglens -std=c99 arglens.c
$ ./arglens foo bar baz fooofooofoo
Computed 5 lens:
0: './arglens' is 9
1: 'foo' is 3
2: 'bar' is 3
3: 'baz' is 3
4: 'fooofooofoo' is 11
Notice how sizeof is computing the size of a run-time sized array. Very much unlike a function.Edit: fix indent for code formatting (hard tabs don't work).
C syntax is already way too complex.
My opinion: a real world wide standard and royalty-free average modern ISA (for instance 64bits RISC-V), then significant system components get a native assembly version, and then some very high level interpreters (javascript?python?ruby?lua?tintin?etc?) written themselves in assembly. If the pre-processor is not abused (aka they are not trying to code c++ with the assembler pre-processor), we should reach a state much less toxic than what we have today.
int16_t a = 20000;
int16_t b = a + a;
But even ignoring size, it can bite you: unsigned int c = 1;
signed int d = -2;
if(c + d > 0)
puts("1 + -2 > 0");
That code prints because of balancing: The signed value gets cast to an unsized int, which can't hold the value.For not directly integer related semantics, creating an out-of-bounds pointer is UB, unless it points to one past the end of the object, in which case you can create the pointer but can't read from it. And if an object's lifetime has ended, pointers to it aren't valid anymore even if you don't even read from it:
void *foo_1 = malloc(1);
free(foo_1);
void *foo_2 = malloc(1);
printf("Checking for same allocatoin: %d", foo_1 == foo_2);
If you go by the standard, strictly speaking this is UB: #include <stdio.h>
int main(void) {
puts("Hello World);
}
But don't worry, real compilers will refuse to compile this. Most don't follow the standard anyways, because they don't treat writing to a memory location as side effect.A large source of gotchas in C are the standard libraries. For example here's a taste of the trouble its locales cause: https://github.com/mpv-player/mpv/commit/1e70e82baa9193f6f02...
puts("Hello World);
How does that even compile without the closing "?I would reinvent being responsible instead.
I would reinvent learning your tools;
I would reinvent being attentive to essential details and
being merciless to accidental complexity.
Unlike the languages that come and go with fashion, the things that matter do deserve constant reinvention."
(last paragraph of the book)
---
can't upvote/ engrave it enough. Amen.
I think this says quite something about the modern human thought process in general. We place a lot of emphasis on knowing how abstract rules we've created should interact and not so much on actually testing things for ourselves.
Sometimes there are unknown factors that will influence results, such as undefined behaviour with C compilers in this case.
Isn’t this the opposite of what should have been done in the case of coding systems for a nuclear facility? I thought the whole point of the exercises was to show that C has lots of undefined behavior, so you should only rely on the behavior of the specific system you’re coding for. If the C standard doesn’t specify what happens when a signed integer overflows, that doesn’t mean you can just ignore it. You could crash the system, report an error, or find out what the targeted system is specified to do in the case of a signed integer overflow. Is there something else I’m missing here, or do the nuclear systems typically have several processors that may have varying behavior for this type of stuff?
In my opinion, the whole point of the exercise was to show that as an engineer, you should have an engineering mindset. And that means collecting requirements, selecting parts, reading a lot of specifications, and participate in writing them.
C is an abstraction. If you program in C, you use that abstraction (so you use the standardized C abstract machine). Why would you program in C and NOT use that abstraction? If you want the latter, just use assembly. Especially in this application.
Otherwise, yes, you hold yourself to the C standard, and you use compilers that are certified to actually implement that standard.
Of course, there needs to be a lot (>50% of the total time) of testing, too. But not to figure out what the compiler does :P
> If the C standard doesn’t specify what happens when a signed integer overflows, that doesn’t mean you can just ignore it.
It means you have to write your programs in a way that signed overflow cannot happen.
> You could crash the system, report an error, or find out what the targeted system is specified to do in the case of a signed integer overflow.
Just make it fail (looong) before the signed integer overflow would happen (with proof).
>what the targeted system is specified to do in the case of a signed integer overflow
What does this mean? What is the "system" in this case?
If the "system" is the hardware, then no. In standardized C, this overflow never makes it down to the hardware. If it's the hardware and the compiler, then sure, but you aren't programming standard C then. I guess you could do that (why would you, though... compliance is gonna reject it).
> Is there something else I’m missing here, or do the nuclear systems typically have several processors that may have varying behavior for this type of stuff?
In practice, you have certified compilers that are certified to actually implement the c standard correctly.
>Is there something else I’m missing here, or do the nuclear systems typically have several processors that may have varying behavior for this type of stuff?
You usually want to be independent of the processor (and/or vendor) used, in order to be able to easily switch it out in case they get uppity/lazy. That's one of the main uses of C.
https://docs.adacore.com/gnat_rm-docs/html/gnat_rm/gnat_rm/r...
Also if someone wrote this bit of obscurantism in any programming language it should be rejected hard when reviewing the code:
return (((((i >= i) << i) >> i) <= i));I use C daily. The answer in each category is "I don't know" because, without the additional information provided by a specific ABI, specific target, and specific compiler, these are all undefined. No language is perfect. It's important to understand the limitations of a language to use it effectively. That is closer to the author's point. This is not a condemnation of C, but rather, an acknowledgement of C, warts and all.
The original point of C was to provide a portable low-level language that could capture expressions instead of writing everything in assembler, so that UNIX could be ported to platforms other than the PDP-11. It's also a reason why C still has uses not shared by newer languages, because these newer languages are more precise. This is a Good Thing, but unfortunately, developers who are unaware of this imprecision can make mistakes that aren't portable and may not behave as they assume. These problems appear, seemingly out of nowhere, when porting source code to a new compiler or a new platform. While the examples the author provides are over-the-top and easy for an experienced C developer to catch, there are more subtle examples, such as promotion and signed integer overflow, that are hard even for an experienced C developer to catch.
This is why I use static analysis, model checking, proof assistants, and even a modern compiler with built-in pedantic checking against the standard. This language has subtle corner cases that even someone with 25-30 years of experience can miss. Unit testing can miss these corner cases unless the right input values are chosen, and the right input values are not always so easy to guess. It's not a condemnation of C or an attempt to evangelize newer languages to point this out, but rather, an acknowledgement that mastery of any language means accepting both its strengths and limitations. C has both.
Different projects have different cultures. Some are quite insular and difficult to break into. Others are quite easy going. For instance, I was able to send a patch through Meson's process (a fix to ensure that their CMake compatibility layer could build custom assembler files) in a matter of days. In projects like OpenBSD, in contrast, you really have to impress the core developers and become part of the community before you can make significant changes. Either way, don't get frustrated, and always remember that these projects are more often than not made up entirely of volunteers who don't owe you or anyone else anything. Be gracious and polite with all of your interactions, even when dealing with the more abrasive personalities. Don't take things personally. See every interaction as a learning opportunity.
If you are interested in a particular project, then I recommend joining the mailing lists and forums. Lurk for a while. Learn the organization and politics of the project, as these will differ wildly between projects. Spend time studying the project and offer help to users in the user mailing list. If they have an IRC channel, join it, and ask the developers on the channel how you can help. They will have specific recommendations based on your experience and specific areas that they need help with.
As you study the project, compare the code as-implemented with the documentation, and begin by offering patches to the documentation and manual pages where these differ. Documentation tends to go stale in many projects since much of the "fun" involves writing the code. With developer blessing, consider zooming in on test coverage, if the project values test automation, and find ways to improve it. This will give you a deeper understanding of how the software operates, and it will help you uncover errors (bugs) that require fixing. Many of these will be inconsequential or minor, but as you learn from the developers and community, and participate in tightening up the code base, you will gain practical knowledge, as well as visibility in the community and respect. Furthermore, learning to maintain and fix issues in a mature project is an excellent way to learn how to contribute feature changes that are accepted, since it will challenge you to learn a lot about the code base, project organization, and community.
Pay close attention to how new features are proposed and developed. One thing that is common in many projects is that feature requests that are ambitious are often rejected, unless the person making the request is a known quantity who is willing to put in the work to see the feature through. Minor error reports and feature requests that are laser focused and that come with a well thought-out patch set implementing the feature or fix tend to be much better received. Most projects are willing to take in code that feels like it belongs (follows style, testing, and similar guidelines) and that is well developed. Since you are starting out, don't try to be too ambitious. You'll get a feel over time regarding what feature requests can be accepted, especially if you provide a patch in the request.
All of this being said, in the age of github, where anyone can start a project to scratch a personal itch, also consider creating a minor library that implements something that you care about. Keep this library small and laser focused. Go through the process of getting it to work on Linux, Windows, MacOS, FreeBSD, OpenBSD, NetBSD, etc. Learn about cross-platform build systems, writing man pages, writing documentation, and creating official releases. Try to find friends and colleagues willing to test out the library and provide you with feedback. While this is an open ended suggestion, you can learn a lot on your own about the sorts of problems that you need to solve as an OSS developer by trying your hand at creating and maintaining a small library on your own.
The important thing is to commit to realistic goals and be tenacious. There is a lot to learn, and at times, you will get frustrated. Don't give up. Accept reasonable criticism, but learn to ignore the trolls. Always be open to learning new things, and accept that people get VERY PASSIONATE about this stuff. Heated exchanges and insults are unfortunately quite common in this space. Try to take the high road by being polite, and don't get pulled into a flame war. Certain maintainers seem to like flaming newbies for fun. It's best to avoid those communities entirely, but if you can't, then invest in a good pair of asbestos coveralls.
Good luck, and I sincerely hope that you get involved! The OSS community needs developers, and we all start where you are, more or less.
For example, here's a GCC-supported target that's available on Compiler Explorer, where the result of question 1 is "3", and question 2 is "1": https://godbolt.org/z/MjT8YhrTc
"it's not doing anything weird" only to people who do already know the C standard inside out. But there is a significant amount of people who might not know everything C (or might know that there are some weird things about types, but still assume 'int' will be at least 4 bytes or something).
It's of course not a question of much practical impact (for anyone not working in embedded at least) but it's nevertheless one that can be at least interesting to some.
Furthermore, just because your code works with Reasonable Compiler 1, it does not mean it will work with Reasonable Compiler 2. I think I have seen enough C compilers that, for each of these questions, you could pick a pair giving different answers.
What Intel processors do is ignore the upper bits of the shift quantity, so it’s effectively (1ULL << (x % 64)) - 1, therefore the function that should have set all ones for x=64 actually set all zeros.
And when I saw answers I smiled, Right! because he didnt specified platform.
Yeah C can be devious, but I still love it! Its my favorite language. And Ruby for scripting.
Even including knowledge of what is IB and UB, C is still simpler than most languages in common use these days.
If C could have a consistent set of rules, and/or easily tag something as undefined a la "unsafe" or have some sort of visual reminder signal (like using function name prefixes or suffixes) that would go a long way to making it better.
But nowadays UB is something much more complex and dangerous than "I can't ever know the results of this".
That depends what you mean by simple. C is a fairly small language, but it has far more than its share of footguns.
In terms of compiler engineering, sure, C is comparatively simple.
Having less keywords and implementing less fancier concepts
doesn't make my day2day life easier, actually it usually makes my day harder.
The bigger issue is the mediocre string processing libraries that are so common to C.
I probably wouldn't write one in C today, but webapps are one of the easier string-heavy things to write in C[1]; you can get away with using a hierarchical memory manager and just free everything after the request is complete.
1: Having to do a lot of string manipulation is usually a good sign "you shouldn't be using C" There's a reason awk was written in 1977.