13 ms·
The Little C Function From Hell
- scott_s 14y agoIf this sort of thing is interesting to you, the author and his colleagues wrote an excellent PLDI 2011 paper about their research which systematically checks various compilers for exactly these kinds of bugs: "Finding and Understanding Bugs in C Compilers": http://www.cs.utah.edu/~regehr/papers/pldi11-preprint.pdf http://www.cs.utah.edu/~regehr/papers/pldi11-preprint.pdf Perhaps my favorite part of that paper is the fact that there is no ground truth (section 2.6). They discover bugs by testing random programs against multiple compilers. If the result from any of the compilers disagree, then there must be a bug. (They guarantee that the inputs are legal.) In theory, it's possible that all of the compilers could be wrong in the same way, which means they wouldn't discover a bug. In practice, this is extremely unlikely. But you can't know for sure. (In practice, they never saw an instance where there were three different results from three compilers; at least two of the compilers always agreed.)
- Deestan 14y ago> They discover bugs by testing random programs against multiple compilers. If the result from any of the compilers disagree, then there must be a bug. How does this make sense? If the result differs from the specification, it is a bug. If the result is unspecified in the specification, the different compilers can differ as much as they want without any of them being considered buggy.
- loumf 14y agoI took "They guarantee that the inputs are legal" to mean that they limited it to programs with specified behavior. They don't know what the behavior is -- just that it is specified. If they can do this, it finds a subset of bugs, with no false positives.
- Wilya 14y agoFrom the linked paper: "Although this compiler-testing approach has been used before [6, 16, 23], Csmith’s test-generation techniques substantially advance the state of the art by generating random programs that are expressive—containing complex code using many C language features—while also ensuring that every generated program has a single interpretation. To have a unique interpretation, a program must not execute any of the 191 kinds of undefined behavior, nor depend on any of the 52 kinds of unspecified behavior, that are described in the C99 standard."
- scott_s 14y agoBoth loumf and Wilya are correct. In support of their answers, remember that the specification does not specify the results of interesting programs. It says "if you do this, this must be the result." But if you limit yourself to only testing such simple cases, you're not going to find any interesting bugs - because such simple programs are likely to have already been tested.
- MidwestMuster 14y agoIsn't this called "fuzzing"
- dllthomas 14y agoIt's certainly related. The difference here is that 1) they're comparing output of multiple systems, rather than looking for obviously erroneous behavior of one (segfaults, memory leaks, failed assertions); and 2) the input data is all correct - fuzzing (per my understanding) usually implies tossing bad data in to see if the system breaks (frequently just slightly bad data is more interesting than complete garbage, but either falls under "fuzzing").
- scott_s 14y agoIt's rather like inverse fuzzing. So, zuffing.
- _delirium 14y agoThis kind of coinage is a rather large rabbit hole! Once upon a time in 1963, someone asked: what happens if you take the Fourier transform of a Fourier transform? Well, a Fourier transform gives you a spectrum, so let's call a Fourier transform of that, a new concept called a cepstrum. So what are its bins, analogous to frequency bins? Let's call them quefrency bins, and the cepstrum is therefore a quefrency cepstrum. What's the operation when you modify quefrencies in the cepstrum in some manner other than uniformly, analogous to how one might run a frequency spectrum through a frequency-domain filter? Why, liftering, of course.
- andrewcooke 14y agoin case anyone else is confused - it (a cepstrum) is the ft of the log of the modulus of an ft. the ft of an ft is the original signal. https://en.wikipedia.org/wiki/Cepstrum https://en.wikipedia.org/wiki/Cepstrum
- cube13 14y ago>If the result differs from the specification, it is a bug. A large part of the C standard is implementation defined(see acqq's post here: http://news.ycombinator.com/item?id=4131828 http://news.ycombinator.com/item?id=4131828 ), so the result could be different on multiple compilers, not a bug, and STILL completely within spec.
- scott_s 14y agoIf I recall correctly, they only generated programs that had well-specified behavior. Not just legal, but specified.
- silentbicycle 14y agoC compilers can be buggy, particularly when you start working with vendor-supplied compilers for embedded platforms. A colleague was furious when he realized that his board's compiler didn't support function pointers.
- joshAg 14y agothat does seem like a rather large omission. how did he work around that issue?
- pmjordan 14y agoI could imagine a DSP architecture that doesn't intrinsically support indirect jumps. (especially as DSPs frequently use the Harvard memory model) That would make implementing function pointers tricky. I'd probably work around this by making a set of dispatch macros that expand into a giant switch block where each case is a (static) function call. The other option would be self-modifying code, which is annoying to do, to say the least, particularly for Harvard systems.
- kragen 14y agoIf your CPU supports keeping function return addresses on a stack that you can push other things onto, you can do an indirect jump by pushing the address you want to jump to and then "returning" to it. That's a lot easier than self-modifying code or massive switch statements, and just as easy on Harvard as on von Neumann architectures.
- silentbicycle 14y agoTo be honest, I don't know, except that there was a lot of scowling. I think it was a PIC micro.
- DanielBMarkham 14y agoI confess to just scanning the code and being cold on C right now, but isn't ++x a post increment? That is, it occurs after the rest of the expression has been evaluated? (as opposed to x++, which is a pre-increment) Just guessing that the perhaps the issue is when the actual overflow is occurring.
- deleted 14y ago[deleted]
- deleted 14y ago[deleted]
- dag11 14y ago++x evaluates to x's new (incremented) value. x++ evaluates to x's old (pre-incremented) value.
- vhf 14y agoIt is the opposite, like in many other languages. e.g. int i = 0; printf("%i %i", i++, ++i); // prints "0 2" Same goes in C, C++, Java, PHP, ... [EDIT] Turns out this is a bad example, as "the order in which function arguments are evaluated is undefined" (cf. below) Correct is : int i = 0; printf("%i", i++); // prints 0 printf("%i", ++i); // prints 2
- simias 14y agoI believe you trigger an undefined behaviour there. You modify i twice in the same statement.
- excuse-me 14y agoIs that defined behaviour? Is there any rule saying that args to a function have to be evaluated in a particular order - ie is ',' a function point?
- decklin 14y agoActually, the order in which function arguments are evaluated is undefined. http://c-faq.com/expr/comma.html http://c-faq.com/expr/comma.html You can use a comma in other expressions to introduce a sequence point: http://c-faq.com/~scs/cgi-bin/faqcat.cgi?sec=expr#seqpoints http://c-faq.com/~scs/cgi-bin/faqcat.cgi?sec=expr#seqpoints
- acqq 14y agoBefore starting reading everything note that author assumed when writing the article that (provided sizeof( int ) > sizeof( char )): char c = (char)128; printf( "%d\n", c ); should always be -128, whereas his commenter Mans (March 4, 2011 at 4:15 am) points out that this conversion is implementation-defined according to the standard, that is, compiler authors are free to decide what the result of such conversion should be.
- dchest 14y agoShould the implementation-defined behavior be always the same? That is, char a = (char)128; char b = (char)128; Will a == b for every implementation?
- lmm 14y agoYes; that's the distinction between "implementation-defined" and "undefined" behaviour.
- beagle3 14y agoWhile that's how it is generally understood, there is nothing stopping the implementation from defining the behaviour as: conversion is rounded up to the nearest multiple of 20 on odd lines. conversion is rounded down to the nearest multiple of 17 on even lines. Older versions of gcc would have such a (fully standard compliant) behavior when you used #pragma, that included running rogue or nethack and other stuff -- but later versions actually succumbed to implementing useful pragmas.
- TazeTSchnitzel 14y agoI'd be surprised if it's non-deterministic, so yes.
- dllthomas 14y agoThat depends on what you mean by "should". Is it required by the standard? AFAIK, no. Would it be a braindead decision on the part of the compiler writers to do otherwise? Almost certainly. In practice, the answer to > Will a == b for every implementation? is, I suspect, yes.
- raverbashing 14y agoA little C tip I learned from hard experience NEVER, EVER, NOT IN A MILLION YEARS use a signed int/char etc, unless you are 200% certain you're doing the right thing (that is, it's for something specific you need it) You WILL have problems, period. "Oh it's just a matter of knowing the C spec" then please go ahead as I grab the popcorn.
- Roboprog 14y agoThere's a certain aspect of "functions have domains, not just ranges" at work here as well -- e.g. - restricting the (math) tan() function to the domain of -90 to 90 degrees (exclusive), unless you really get off on watching it cycle over madness. If you are going to be playing around the edges of something, it behooves you to put some kind of pre-condition in with an assert of similar mechanism. In fairness, I guess a function like this is a good example of why you should put in preconditions, as well as a good demonstration that "not all the world is a VAX" (nor MS C 7, nor GCC version N) :-)
- timbre 14y agoI'm rusty on C, and confused. What should I use instead of signed int?
- dchest 14y agoJust tried with Plan 9-derived compilers shipped with Go, and there's no bug (provided that my re-implementation of the test case is correct).
- Arcticus 14y agoDan Saks did a great set of presentations called "C and C++ Gotchas" on these types of things at the 2006 Embedded Systems Conference in San Jose. Sorry couldn't find a link that wasn't behind a paywall but here is one for reference. http://eetimes.com/electrical-engineers/education-training/tech-papers/4125901/C-and-C--Gotchas http://eetimes.com/electrical-engineers/education-training/t...
- sltkr 14y agoTo be absolutely accurate, the program still invokes implementation-defined behaviour. From the C standard on casting integers: “if the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised”. Therefore, the author's conclusion that “the behavior is well-defined and every correct compiler must emit this output” is plain wrong. A correct compiler might emit a signal instead of outputting anything. (However, printing 1 for the last case is still wrong, because there is no possible way for ++x to yield a value greater than INT_MAX, so this cannot be consistent with any implementation-defined behaviour.)
- sltkr 14y ago^ In the above, I meant CHAR_MAX instead of INT_MAX. Oops!
- malkia 14y agoThat's undefined behavior, the compiler can do whatever it pleases to. It can even print 666, and be done.
- AceJohnny2 14y agoNo it's not. I had the same thought, but the author carefully points out from the standard: "The usual arithmetic conversions ensure that two operands to a “+” operator of type signed char are both promoted to signed int before the addition is performed." He does assume sizeof(int) > sizeof(char), which is true on all platforms he has tried. It would be undefined on an AVR or other microcontroller where sizeof(int) == sizeof(char) though.
- malkia 14y agoThanks! Should read the article more carefully.
- nova 14y agoundefined on an AVR or other microcontroller where sizeof(int) == sizeof(char) though. Just noting that ints are 16 bits wide in AVR-GCC, unless you use the -mint8 option which violates C standards.
- JoachimSchipper 14y agoAbsolutely true. Note, though, that sizeof(int) == sizeof(char) is allowed if you have 16-bit chars.
- cperciva 14y ago16-bit chars aren't allowed in modern versions of C -- CHAR_BIT is required to be 8.
- JoachimSchipper 14y agoThanks for the update! (For the curious: C99 or POSIX both require CHAR_BIT == 8.)
- TwoBit 14y agoSummary: ++x for signed char is supposed to convert x to int before the ++, but some compilers get it wrong.
- Dove 14y agoYou know, not long ago I took somebody's "how well do you know C?" quizzes, and it was fully of this sort of question -- what C does with overflows and underflows in various circumstances. And I must admit, I felt like I had been asked what happens, exactly and specifically, to a particular piece of memory after dividing by zero. "I don't know, I try to avoid doing that!" I don't know. I can admire the analysis, but I don't understand the motive. Do people really write code that relies on this sort of behavior? Or is it just trivia for trivia's sake?
- egonschiele 14y agoI do similar deep digging for some topics. It may seem useless, and a lot of times it is. But sometimes digging into a problem helps me understand the bigger picture better, and then it seems worthwhile. Lately I've become more picky about what I'll dig into though.
- pgeorgi 14y agoIt's interesting when trying to do automated code analysis, and C is an important target for that, since it's used everywhere. But computer programs have a hard time to know when type limits are important and when they're not (or in fact not anticipated by the developer) - so they have to cover all cases. (IMHO) For obscure cases, there's ideally some clearer version of the same behaviour that could be recommended to the developer - either helping them to find a potential error or to have them use a less ambiguous and easier to understand notation.
- rcfox 14y agoIf it was a week or two ago, the quiz was probably from the same person as this article. He's not just doing it for fun; he's a professor at the University of Utah, and he's researching this area, looking for bugs in compilers. In fact, he's developed a tool for this: http://embed.cs.utah.edu/csmith/ http://embed.cs.utah.edu/csmith/ These tiny bits of strange code are condensed versions of what you might see in the wild, especially after preprocessing. Nobody's doing ++x > y, but they do something that looks reasonable like foo(x) > bar(x), where foo() and bar() return chars.
- WalterBright 14y agoThe Digital Mars C compiler returns the correct answer with or without optimization turned on.
- robot 14y agoThe user must know about overflows and act accordingly. Compiler behavior may naturally change based on optimisations since it is undefined territory.
- krollew 14y ago"That’s a lot of trouble being caused by a two-line function. C may be a small language, but it’s not a simple one." I disagree. C is very simple. You need to know C is not suppoused to work the same on platform and I guess behaviour you have tested is not defined by standard. I think every good C programmer know when he have to be causious because behaviour may be platform dependent. In matter of fact you did as well. I guess case you've studdied is not common to be used in real code. If so, there is very easy solution: #if ((char)CHAR_MAX) + 1 > ((char)CHAR_MAX) /* some code here */ #else /* some code here */ #endif There is no problem to me.
- cperciva 14y agoEvery problem has a solution which is simple, elegant, and doesn't work. This is it. Section 6.10.1, paragraph 4: "... For the purposes of this token conversion and evaluation, all signed integer types and all unsigned integer types act as if they have the same represenation as, respectively, the types intmax_t and uintmax_t..." Inside preprocessor directives, your chars aren't chars any more.
- krollew 14y agoSo what they are? Why it doesn't work? Your quote don't clarify.
- cperciva 14y agoYour "char" in a preprocessor directive is either a uintmax_t or an intmax_t. Either way, it's going to end up as #if 128 > 127 or #if 256 > 255 -- so the first case will always end up being included.
- krollew 14y agoIt's standard behaviour or one compiler does so? Outside preprocessor char has another meaning? Thanks anyway.