70 points · by ingve · 9y ago · 116 comments
I suspect we could use a crawler that detects this phrase applied to a programming language, and use that as a proxy metric for programming language design quality. (The more unique detections of the phrase, the worse the language.)
For every developer who reads your comment and learns something, there's going to be one who commits a bug based on this issue to a production repo without realizing it. When it comes to discovering this kind of minutia in programming languages, it basically goes down one of two ways: Either you randomly stumble across information about the hazard on stack overflow (or hacker news, in my case), or you blunder right into it at least once. I call these kinds of quirks "landmines".
I prefer my languages landmine-free, or as close to it as we could hope to achieve. This kind of behavior is definitely not something to make quips about, it's exactly the kind of language flaw that might cause government software to bill incorrectly calculated invoices to people who can't afford it, or overbook planes and cause confusion at airports. Maybe I've misinterpreted your comment, but your comment reads like you think of this sort of detail as "separating the men from the boys". It's totally not doing that. What it's really doing is randomly blowing up civilians.
What I'm really trying to say is that as an industry we need to stop proping up C as if it's some golden god. Was it a good compromise for it's time? Of course but we can and should do better because it's clear that writing 'good' C code might be beyond the realm of man.
Writing good C code isn't impossible, it just requires more resources than writing poor C code. A lot of places aren't willing to put the resources in to write good, secure code, in any language.
Just as a litmus test: In how many languages can you cause the SIMD shuffle instruction to be used, explicitly? How many have compilers that can take advantage of it?
JVM / .NET languages don't do this (I know .NET can do SIMD, but it can't do shuffle). Rust can maybe do it? Not sure on the status. Dlang SIMD support seems only partial.
Which can do a popcnt explicitly or automatically?
There are lots of little holes in other languages just in the space of "Can I even use the instructions the cpu has". Then of course being able to control memory completely is a huge advantage in some domains. Any language that lets you do that will have most of the same danger problems as C or C++
I'm sure you could come up with something that is a little safer with as much power, but it isn't so easy for someone to just stop using C/C++ right now if they need that control.
But I agree with your general sentiment that currently C/C++ is the only choice for certain domains. But there is nothing theoretically stopping us from creating safer system languages. (See Rust and Swift, much less so Swift. But Apple is working towards that goal with the option to disable reference counting in a future version which will give much more predictable performance.)
My argument is that we need to stop pretending that C/C++ is not worth improving. Every time someone criticizes a gotcha of C/C++ HN gets very defensive. We need to kill our gods if we want better ones and I personally think we need better system programming languages because it is far too easy to write bad C/C++ code.
- In a bare expression, with only the variable: `i++;` (That's what usually goes into `for`.)
- In a simple assignment, without any extra expression: `int a = b++;`
- While updating an array index that appears nowhere else: `v[i++] = 0;`
Using it anywhere else is asking for trouble. In C++, using the last one is also asking for trouble.
You're writing C, don't give me the "I might not know that what I'm calling is a macro" argument. You better know what you're calling in C. If you don't want to know what you're calling, don't write C.
It's not uncommon to replace a function with a wrapper macro later on in an attempt to debug something or trace execution or whatever. It's not really realistic to expect that when such a replacement is done that they go analyze every possible call site to see if sizeof() results in side-effect evaluation or not.
This is just another case of C being a language built out of undefined behavior.
That puts a de-facto cap on either the speed of C development or the size of C projects.
It is definitely possible to have a project so large that no one person can understand it all. So either you can't have C projects larger than whatever that size is, lest you risk not knowing what you're calling, or you have to accept that developers working on your project will be reading and re-reading parts of source code that haven't changed in years in order to make sure they know what they're calling, rather than re-implementing common patterns in the codebase and trusting to prior diligence.
Either way, you're not selling C to me as a language to embark upon a major project with.
Sounds about right.
I dearly love C, but it's time to move on. Languages like Rust seem to solve most of the major pitfalls while not sacrificing on speed.
If it is the former free to use whatever language you choose. If it is the latter, can you please keep your opinion as just that.
I believe we are all adults here and quite capable of making judgment calls.
Rust has some interesting features and lots of other languages too. No need for the drive by.
You don't need to know the entire project, but you had damn well better understand the code right in front of you that you are editing.
In literally any language, developers who don't understand what they are changing will cause bugs.
Macros (in any language, not just C) are the big problem, because you have to know a macro's definition before you can know precisely what its usage rules are.
Without macros, C projects can get as large as they like. Everyone must be required to know the language, but you can work on any plain-functional project given that knowledge.
Once you start #define-ing tons of preprocessor macro-functions, all bets are off; now your project is essentially its own language that every developer must first familiarize themselves with before usefully contributing, and that does indeed put "a de-facto cap on either the speed ... or the size" of projects.
Not true, see: https://doc.rust-lang.org/book/macros.html#hygiene (not unique to Rust, though, Scheme even has some of this like Hygienic macros)
Macros don't have to be C-style simple text substitution.
I don't think anybody will disagree.
Don't get me wrong. I prefer working in Python or its ilk, because I prefer a higher level of safeguards. But nothing I work on needs the precision of behavior that C provides. And sometimes you need sharp and precise.
It's definitely true that it's sharp and sometimes (currently) the best tool for the job, but don't ignore the reality of its design and limitations when praising it.
If C gives you enough rope to hang yourself, C++ gives you enough rope to bind and gag your neighborhood, rig the sails on a small ship, and still have enough rope left over to hang yourself from the yardarm.
int vla[nparam];
int *pcopyspace = malloc(sizeof vla);
Here sizeof vla is basically just nparam sizeof(int).vla* is evaluated to the extent of calculating its run-time size.FYI, your mouse is also dangerous, you can easily click the wrong way and send all your money away to someone in Nigeria. Should we blame the mouse?
Agreed that they're a very sharp tool and need to be used with care.
Then your VLA is stack allocated when small and heap allocated when large and works everywhere, even as a return value or other cases where alloca would fail.
(Well, there is a possible reason: lack of integration between longjmp and unwinding cleanup mechanisms. I'm not 100% certain here, but I think VLA's are supposed to be cleaned up when abandoned by longjmp. Mind you, longjmp will also outsmart your std::vector.)
As far as dedicated tools, my best experience is with Coverity, which seems to have a design focus of finding errors in codebases with a minimum of false positives.
#include "stdio.h"
int main () {
/* local variable definition */
char grade = 'B';
int a = 1;
switch(grade) {
printf("great!\n" );
a = a + 1;
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
printf("a: %d\n", a);
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade );
return 0;
}I mean, I totally get that this is a really poor use case, and as I just learned from looking it up (because I didn't know this before), sizeof in C isn't a function or macro, but an operator.
That just doesn't jibe with the mental model of C that I had in my head. And programming languages, if anything, should be conducive to mental models, not hostile to them.
I'm curious, what mental model of sizeof() did you have in your head, and how did it work?
>Where a size expression is part of the operand of a sizeof operator and changing the value of the size expression would not affect the result of the operator, it is unspecified whether or not the size expression is evaluated.
I think it's a long-winded way of saying "my bad"
We're not all fitted with the same Umbrella IntuCard Mk. II Intuition card so that, relying on intuition alone, we can all reach the same results from the same inputs. Relying on intuition to figure out how a language works is about as smart as relying on intuition to figure out the limit of a series, how a telephone work or how a transistor works -- all three of which have been definitely designed for humans to use, since there were nothing but humans who could use them back when they were invented.
I don't like it any more than you do, and my life would be much easier (and probably happier) if it weren't like this, but blaming it on the language is the equivalent of the turtle blaming calculus after losing the race to Achiles.
The problem, however, is whether we call ourselves "engineers", and not just "coders". Real world engineers take responsibility for anything related to their project, even if it's not their job.
Flying instructors often teach "everyone is stupid for 15 minutes a day". That's why every plane control is made to prevent errors, even if other prevention measures failed. Of course, we often don't need that kind of reliability in computer programming.
But in cases when we really do "engineering", and not just "programming", we want to prevent shooting to the foot, even when user points out gun to their foot and pulls the trigger. That's why they put safety switch on guns.
"When I poke myself in the eye, it hurts."
I don't think in 40 years of programming in C and C++ I have ever seen an example of someone doing something with sizeof() quite that weird, and I've seen plenty of weird things.
Plus one for the happy ending that they won't be doing that again.
Edit: Now I see the issue. Still, this should be easy to avoid. Don't use expressions with side effects as the input to a macro.
Correction: sizeof working_array is equivalent to...
Not classic C90; only the brain damaged C99 dialect.
Prior to C99, sizeof expr is a constant expression, always.
You can easily program in C90. Plenty of currently maintained or even new projects are C90 only.
If using gcc, use gcc -ansi or equivalently -std=c90, and there you are.
There is a way to detect (albeit at run time) when a macro is given an expression which contains side effects. This:
http://git.savannah.nongnu.org/cgit/kazlib.git/tree/sfx.h
compile the sfx.c into your code, along with the except.c and hash.c modules. Then you can use the SFX_CHECK macro in your macro bodies. For instance, the dict.h header file uses it like this:
#ifdef KAZLIB_SIDEEFFECT_DEBUG
#define dict_isfull(D) (SFX_CHECK(D)->dict_nodecount == (D)->dict_maxcount)
#else
#define dict_isfull(D) ((D)->dict_nodecount == (D)->dict_maxcount)
#endif
If the debugging is enabled, and some place in the application calls dict_isfull(d++), then there will be a diagnostic, thanks to code generated by SFX_CHECK(D), which parses the expression (or pulls the parse out of a cache) and then diagnoses based on the results. Unfortunately, this is a run-time check: the expression has to be stepped on.(A bit of work could turn this into a static system. E.g the macros could spit out a special annotation, then the output of gcc -E could be collected and post-processed to look for the annotated material and determine if there are side effects.)
I wrote this in around 1999 and it hasn't been maintained since.
The parser has to work with incomplete information and hence deal with ambiguities. For instance (a)(b) could be a function call or a cast of (b) to the type (a). We don't know and so we have to conclude that this is a "maybe side effect" (function call). In the face of ambiguities, we parse the expression multiple ways. If it parses correctly in two ways, we conclude pessimistically: if one of the ways of parsing it suggests there is a side effect we go with that. If errors are encountered in some of the parses, backtracking takes place, and this is done with the help of exception handling, which is built on setjmp/longjmp.