7 ms·
C is not your friend: sizeof and side-effects
- buserror 10y agoAh, the weekly 'C is evil' HN bit. 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?
- Etzos 10y agoThis seems like a bit of a knee-jerk reaction on your part. The article itself is interesting and points out an edge case which is likely to trip people up in certain situations. I don't really see the article mentioning or even hinting that "C is evil", it even includes a bit of a qualifier at the end: "C is reaching PHP-like levels of confusion here, but luckily for us this combination . . . is pretty hard to hit. I’ve never seen it in “real” code."
- blackflame7000 10y agoTo be fair the article is called "C is not your friend"
- buserror 10y agoA bit yes, I have to admit this. However it's not HARD to find new&interesting way of screwing up with the language, it's been done for longer than I'm alive, and some people abused it in extraordinary ways over the years [0], so all I can think of when I see that sort of article is 'HN clickbait'. It works. It's actually borderline trolling at this rate. [0]: http://www.ioccc.org/ http://www.ioccc.org/
- mpweiher 10y agoIf you use ++ in a sizeof expression...you're probably getting what you deserve. C may not be your friend, but it is fair.
- breadbox 10y agoThe issue is that sizeof is most often used in function-like macros, and the user may not even realize that it's a macro. (Or that sizeof is involved in it.)
- tobyhinloopen 10y agoWell the user should check what that thing is you're calling, or use it with caution (ie not using side-effects as params)
- marcosdumay 10y agoThe reasonable places you can use `++` and `--` in C are exclusively: - 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.
- syncsynchalt 10y agoThe deeper you get into C++ the more you realize that Swift made the right call by removing all four inc/dec operators.
- marcosdumay 10y agoIn-place manipulation of values is a troublemaker. C is too old for its creators to know that, given that it's the language where people got to learn that. But no newer language should carry them.
- RubenSandwich 10y agoI'm not sure what a fair or unfair language would be. Is an unfair language one who's compiler output is non-deterministic? If that is the case then C fails that test with undefined behavior. 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.
- knieveltech 10y agoThis feels like a rant about a language handing bad developers enough rope to hang an entire village. I'm unconvinced this represents a failing of the language.
- thesmallestcat 10y agoI thought it was C++ that gave you enough to hang the village. I'm not sure who said it, but it's one of my favorite PL-related quotes: 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.
- kazinator 10y agoC++ refused to give you the rope; they left it in the SGI template library: https://www.sgi.com/tech/stl/Rope.html https://www.sgi.com/tech/stl/Rope.html
- empath75 10y agoIt might not be a failing of the language, but it might be a reason not to use it all the same.
- knieveltech 10y ago"Use the right tool for the job at hand." and "A poor craftsman blames his tools." are axioms in every industry and craft.
- tdb7893 10y agoI think in software engineering it's prudent to just assume that all developers make mistakes sometimes. Anything that can have developers make less mistakes or can catch developer mistakes saves time (and therefore money) in the long term so I think it's fair to complain that c makes mistakes easy and difficult to catch.
- 10y ago
- breadbox 10y agoThis flaw was pointed out while C99 was under review. The idea of changing sizeof to not be evaluated at compile-time did not sit well with a lot of people. Unfortunately, the alternative (sizeof not being usable with dynamic arrays) was clearly worse.
- bvda 10y agoDo you happen to know why that was perceived as worse? If I understand correctly the difference would be that you'd have to write (i * sizeof(char)) vs. (sizeof(char[i]))? Personally I'd even prefer the former.
- gandalf013 10y agoA very common idiom is "T p = malloc(n sizeof *p)". That only works if sizeof doesn't evaluate its arguments.
- kazinator 10y agoWhy not? Suppose you have a C99 VLA object, and you want to malloc the equivalent amount of space. Couldn't you just do this: 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.
- jstimpfle 10y ago> sizeof (char[i]) is equivalent to i * sizeof char, and will be evaluated at run time. Correction: sizeof working_array is equivalent to...
- jstimpfle 10y agomy bad, "sizeof (char[i])" actually works!
- mikeash 10y agoIs this a pitfall people actually fall victim to? It's an interesting corner case, to be sure, but has anyone been bitten by it in real work?
- mfukar 10y agoI doubt it. Expressions like this raise all sorts of red flags in code review.
- gpvos 10y agoIt shouldn't be too hard for compilers to warn about this, I think.
- tobyhinloopen 10y agoC is a language that gives you a very sharp laser knife that can cut everything clean off very efficiently and fast. However, without care, you'll cut your fingers off. Always wear safety goggles around dangerous equipment and don't do stupid things like i++ inside a macro call. 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.
- Sir_Substance 10y ago>You better know what you're calling in C. If you don't want to know what you're calling, don't write C. 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.
- bandushrew 10y agoI have no interesting in convincing you to use C for anything, but it IS true in absolutely any language that if you are changing it, you should know what you are changing and how it works. 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.
- derefr 10y ago"What you're calling" in the sense of "what the syntax elements, language-intrinsics, and macros you're using mean", not "what you're calling" in terms of plain-function APIs. 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.
- joatmon-snoo 10y agoThis comes with me not being very experienced or familiar with C, but this is... disturbing. 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.
- jjnoakes 10y ago> That just doesn't jibe with the mental model of C that I had in my head I'm curious, what mental model of sizeof() did you have in your head, and how did it work?
- ori_b 10y agoBut it can't be a function, because functions don't have access to that information.
- notalaser 10y agoOne could equally point out that programmers should form mental models by reading documentation, rather than relying on intuition. It's not like you have to dig through compiler sources to find out that sizeof is an operator. Even if it wasn't plainly documented in pretty much any properly-written material on the C programming language, it's pretty obvious that sizeof can't be a function, since a function doesn't have access to the sort of data required in order to retrieve this sort of information.
- dbaupp 10y agoThe reality is people form mental models by intuition. Things designed for humans to use (like programming languages) should take this reality into account.
- bandushrew 10y agoThe reality is that any model formed for any programming language that isn't based on reading the documentation has no chance of being correct...
- kbradero 10y agoc is not your friend as a knife is not.
- benchaney 10y agoI don't understand why this would come up. When would you ever use ++ on the result of evaluating an expression. 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.
- faragon 10y agoC is OK: it is not your friend, it is a tool.
- woliveirajr 10y agoThe beauty of C/C++ is exactly that it gives you freedom to do things. Period. There are a lot of languages designed to limit you (or make safer programs, you name it). Some might be faster / more productive / safer / environment-friendly, use what you think you should. But don't try to limit C, please.
- self-diversity 10y agoThen stop writing important code that can cause me harm when inevitably easily exploited because of that freedom, please.
- klodolph 10y agoYou can see why VLAs were made optional in C11, even though they were mandatory in C99. There were just too many weird interactions that VLAs had with other parts of the language. (That, and it was an easy way to get a stack overflow.)
- vvanders 10y agoComing from C++ VLA are one of things that I really wish I had access too. The number of times I've seen stuff created on the heap just to toss at the end of the block in production code always made me cringe. Agreed that they're a very sharp tool and need to be used with care.
- cperciva 10y agoIf you want to allocate from the stack, you can usually use alloca.
- sigjuice 10y agoAnd nothing bad will happen if you alloca too much?
- cperciva 10y agoExactly the same bad things will happen as if you declare a variable-length array.
- wahern 10y agoMemory from alloca has function lifetime, while VLAs and compound literals have block scope. In a loop alloca could easily blow your stack even if you limit each allocation to something small. This is a serious pitfall, especially when using alloca with macros. The reverse is true for VLAs and compound literals in macros that return a pointer--the caller might not know that the lifetime is block-scoped and not function-scoped. Also, alloca and VLAs aren't necessarily implemented the same way. When instantiating a VLA a compiler might extend and test the stack pointer in page-sized increments so an allocation doesn't extend past the guard page without triggering a segfault. An alloca implementation might not.
- headcanon 10y agoIs there a kind of "linter" for C that spots stuff like the problems presented here (as opposed to just formatting)? What kinds of static analysis are available here?
- syncsynchalt 10y agoThere are lots of useful -W flags to gcc/clang that expose language pitfalls (examples: -Wparentheses and -Wshadow). 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.
- MooMooMooney 10y agoC of course is not your friend, C is always computer's friend.
- camgunz 10y agoJamming `++` and `--` everywhere is bad. Don't do it. Hooray we can use C again.
- kazinator 10y ago> The length of the working array depends on the value of i. 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 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.
- socmag 10y agoFile under: "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.
- deepsun 10y agoMany people comments can be reduced to "Yes, you can shoot yourself to the foot. Don't do that". 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.
- jasonlhy 10y agoC is a very "strict" language. It do the right thing only if you write the right code. It has many undefined behaviors. One of the undefined behaviors I found when I studied the compiler course. The purposed grammar from https://www.amazon.com/Programming-Language-Brian-W-Kernighan/dp/0131103628/ref=sr_1_1?ie=UTF8&qid=1492654731&sr=8-1&keywords=c+programming https://www.amazon.com/Programming-Language-Brian-W-Kernigha... allows this kind of structure, there can be statements after the switch but before the case labels. gcc also accepts this, but those statements will not be executed. Note: code modified from https://www.tutorialspoint.com/cprogramming/switch_statement_in_c.htm https://www.tutorialspoint.com/cprogramming/switch_statement... #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; }