r/compsci • u/bgeron • Jan 20 '13
C and C++ Aren’t Future Proof
http://blog.regehr.org/archives/88022
u/Neotyguy Jan 21 '13
I'm confused. Wouldn't this be an argument for saying that current C/C++ compilers aren't future proof? It seems like this has nothing to do with the languages' standards, but more with GCC and Clang.
16
u/minno Might know what he's talking about | Crypto Jan 21 '13
The problem is that almost all C and C++ programs use undefined operations that are treated consistently by compilers, so programmers rely on those behaviors. The compiler makers are under no obligation to continue treating those operations consistently, and they often don't, which breaks existing code that worked just fine before.
16
u/Neotyguy Jan 21 '13
So then shouldn't programs not rely on those undefined behaviors? This seems to me like it is more of a problem with how people write code than the compilers themselves.
17
u/gsg_ Jan 21 '13
People should write code that doesn't exhibit undefined behaviour, but they usually aren't careful enough to do so.
This is not likely to change.
4
u/workman161 Jan 21 '13
If someone uses undefined behavior and that behavior later changes, thats their fault, not the standard's.
14
Jan 21 '13
pointing the finger doesnt make the broken code go away
5
u/workman161 Jan 21 '13
Nor does it make it any less their responsibility. The standard is not responsible for broken code.
2
u/SanityInAnarchy Jan 21 '13
However, formally defining things in the standard would prevent a lot of broken code. So would more severe compile errors.
1
Jan 21 '13
i dont care who is "responsible". figuring out who is to blame isn't productive, its a way of deflecting the issue and saying that someone else should fix it.
4
u/SanityInAnarchy Jan 21 '13
Of course, but regardless of whose fault it is, it is possible to avoid this problem by defining as much behavior as you can. It's not necessarily C/C++'s fault, but it is yet another thing that makes these languages less safe to code in.
For example: In most associative-array and set implementations, the order of iteration through keys and values is undefined. This is because one of the most efficient implementations for an associative array is a hash table, and unless you include some additional way of maintaining order, the order of iteration through a hash table is random.
But you could design an associative array around binary search trees, say, which do have a predictable iteration order. And programmers could start relying on that. Then, later, when you learn that hash tables are a more efficient way to do this, and you swap the tree implementation for a hashtable implementation, all these programs break.
You could also go the other way. Someone could decide that, hey, hash traversal is in random order, I can use that to generate random numbers! So later, if you replace the hashtable with a tree, or if you impose an order on the hashtable, their program breaks. (Especially scary if they were using this randomness in cryptography.)
Ruby actually went the opposite direction here. In Ruby 1.8, iteration through a "hash" (a Ruby associative array) was undefined. You could often get a predictable iteration out of it, though it wouldn't necessarily be sorted. Ruby 1.9 formally declared that hashes iterate in the order in which their keys were inserted. So if you write and test your program on Ruby 1.9, there's no way you're relying on undefined behavior here, because all the relevant behavior is defined. If you were relying on hash iteration to be a certain way, that's now standardized, and won't change in the future.
That's not to say this is necessarily better. Ruby can easily do this, because Ruby is already slow enough that adding an overhead to every hash doesn't really do much. C and C++ are supposed to be fast, so leaving a lot of behavior undefined makes sense, because it means compilers are free to optimize -- in the same way that, if we left Ruby's hash iteration order "undefined", Ruby would be free to choose any associative-array implementation it wanted.
8
u/gsg_ Jan 21 '13
An individual failure is the fault of the programmer responsible: a pattern of many individual failures is a fault in the design of the standard.
1
u/Neotyguy Jan 21 '13
I can guarantee that there are hundreds of missing semicolon errors each day. Does this mean that this is a fault in the standard?
7
u/kubalaa Jan 21 '13
No, because these are defined as errors and caught by compilers. If the standard defined all "undefined behaviour" as an errors and required compilers to detect it, then there would be no problem. The problem is that it's easy to write programs with undefined behaviour and very hard to catch before it causes a bug at runtime.
2
u/gsg_ Jan 21 '13
If syntax errors were a serious failure, would you argue that it was not?
1
u/Neotyguy Jan 21 '13
I would. For the same reason that I would say that capitlization and punctuation are necessary for english communication.
1
u/ironykarl Jan 21 '13
C has a huge amount of stuff left up to the whims of implementers, though. Now, that's exactly what makes it a good language for relatively low-level code that works on a bunch of targets, but it's also a legitimate target for critique of the language.
1
u/moor-GAYZ Jan 21 '13
Undefined behaviour is nowhere near being the same as implementation-defined behaviour.
2
u/ironykarl Jan 22 '13
http://en.wikipedia.org/wiki/Undefined_behavior, fourth paragraph:
In C and C++, implementation-defined behavior is also defined which requires the implementation to document what it does, thus more restrictive than undefined behavior.
To me this indicates that my usage is not outside the bounds.
1
u/TheMG Feb 05 '13
This is making the same assumption that causes these problems to occur: that while these cases are technically undefined, they'll probably do X. Right?
Compilers optimize aggressively, and increasingly so. When they encounter opportunities where behaviour is undefined, they will emit the code that follows the standard most optimally: no code.
8
u/gcross Jan 21 '13
Indeed, that is one of the four options for moving forward that are listed at the end of the article:
We ditch the C and C++, and port our systems code to Objective Ruby or Haskell++ or whatever.
Developers take undefined behavior more seriously, and proactively eliminate these bugs not only in new code, but in all of the legacy code.
The C/C++ standards bodies and/or the compiler writers decide that correctness is more important than performance and start assigning semantics to certain classes of undefined operations.
The undefined behavior time bombs keep going off, causing minor to medium-grade pain for decades to come.
8
u/knight666 Jan 21 '13
We ditch the C and C++, and port our systems code to Objective Ruby or Haskell++ or whatever.
Will never happen, when a company has invested in people who know C/C++, they won't allow them to rewrite everything in a new language because of "a silly bug in the compiler".
Developers take undefined behavior more seriously, and proactively eliminate these bugs not only in new code, but in all of the legacy code.
There's no immediate benefit for doing so and worse, there's no penalty for not doing so. Besides, nobody wants to touch Module X, which was written in the 90's by some kind of genius who has since left the company.
The C/C++ standards bodies and/or the compiler writers decide that correctness is more important than performance and start assigning semantics to certain classes of undefined operations.
Correctness doesn't ship products, performance does.
The undefined behavior time bombs keep going off, causing minor to medium-grade pain for decades to come.
Pretty much this.
4
u/barrkel Jan 21 '13
Correctness doesn't ship products, performance does.
When a program gives wrong results, it doesn't matter how fast it is.
For most programs, correctness is more important than performance, especially small performance gains.
4
u/SanityInAnarchy Jan 21 '13
Will never happen, when a company has invested in people who know C/C++, they won't allow them to rewrite everything in a new language because of "a silly bug in the compiler".
In the same way that COBOL will never die. But this isn't the real obstacle. No one writes web apps in C/C++, for example -- you use at least something like Java.
I don't think C or C++ are likely to go away anytime soon, mostly because there aren't that many other languages that are even close in terms of raw performance, low-level data structures, and general systems programming. But that's the real question to ask, because raw inertia really hasn't prevented these languages from getting utterly spanked in areas where they really aren't suited.
There's no immediate benefit for doing so and worse, there's no penalty for not doing so.
This is problematic. Not because it's actually the case, but because so many programmers believe it's the case.
The immediate benefit is that, especially in languages as dangerous as these, strictness matters. Turning on all warnings won't just find undefined behavior that happens to work, it'll also find actual bugs that really are likely to cause problems sometime very soon.
That's what John Carmack found, anyway, but what does he know?
Correctness doesn't ship products, performance does.
Again, this depends very much on the product domain. Web applications have found just the opposite.
The undefined behavior time bombs keep going off, causing minor to medium-grade pain for decades to come.
Pretty much this.
I agree this seems sadly likely, but I'm still going to push strongly for #2, especially in C and C++. At least in new code.
0
Jan 21 '13
[deleted]
8
u/gasche Jan 21 '13
The author's PhD thesis was about soft real-time schedulers in operating systems, and he has since devoted his life to improving the reliability of embedded systems (see his webpage). I believe he has already seen kernel code, and survived it.
5
u/minno Might know what he's talking about | Crypto Jan 21 '13
I think the author's claiming that it's a problem with the standards lumping too many things under "undefined behavior" when they could have perfectly well-defined behavior, since even well-written, bug-free code turns out to have a lot of undefined behavior.
2
u/Nebu Jan 21 '13
That's not my interpretation of the author's claim.
I think the author sees the problem being more with the attitude of the programmers writing what is technically undefined code, and not caring much, because it works in every compiler they've tried.
I think the author respect the standards' decision to "lump" many things under "undefined behaviour" because it gives compilers freedom to perform more aggressive optimizations (and he presumably also respects any standards that decide to make the opposite decisions, of choosing to define lots of behaviour, even if it means restricting the optimizations which could be done).
I.e. The standards are not the problem. People (selectively) ignoring the standards is the problem.
1
4
u/Merad Jan 21 '13
Quite a few common things are either undefined or implementation defined.
Example: Dereferencing a null pointer. We usually expect it to segfault, but how many C or C++ programmers know that it's actually undefined behavior?
Pointers in general, really. They're fun, but they're a minefield of undefined behavior. Consider:
char a[10] = { '\0' }; cout << *(a + 12);What happens? Logically, we'd expect the value of memory location <address of a> + 12 to be printed, unless it happens to be an invalid address, then I suppose we should segfault. In reality? Sorry, undefined behavior.
4
2
u/TIGGER_WARNING Jan 21 '13
C and C++ are often lauded in discussions on the pedagogical value of various languages specifically because of pointer shenanigans. A lot of people think that students don't really understand pointers without having experienced C/C++ debugging.
2
u/FeanorM Jan 21 '13
Not being an ass: can you (or someone) point me towards an argument that this isn't true?
2
u/TIGGER_WARNING Jan 21 '13
Most of the debates on picking an instructional language center on the tradeoff between flexibility (e.g. ability to do more interesting tasks with minimal experience) and low-level control. So while nobody really argues that C++ doesn't require a better grasp on pointers than, say, Java, they do often argue that the increase in pointer errors and low-level bugs only tangentially related to The Big Picture isn't worth it.
You could also argue that the kind of arbitrariness in deciding which behaviors are defined and which aren't that Merad mentioned above means that knowing what happens in C doesn't do anything for your general understanding of pointers and so isn't Big Picture material at all.
-1
u/NYKevin Jan 21 '13
Example: Dereferencing a null pointer. We usually expect it to segfault, but how many C or C++ programmers know that it's actually undefined behavior?
Dereferencing
NULLis a bug any way you slice it, so this is only an issue in debug builds, and I don't care what kind of compiler you're making, if I pass-g -O0, I expect*NULLto segfault, crash, or otherwise terminate. Do whatever crazy bullshit you want when optimizing, but if you've been explicitly instructed not to optimize, then you shouldn't be optimizing.3
u/Merad Jan 21 '13
if I pass -g -O0, I expect *NULL to segfault, crash, or otherwise terminate.
You pretty much just confirmed my point. You have no guarantee that any of the above will happen regardless of the build type.
0
u/NYKevin Jan 21 '13
I know that. But if the compiler is dumb enough to perform optimizations when I specifically told it not to, I'm switching compilers. And if it doesn't optimize, then the code will literally try to access address 0 and crash.
3
u/Merad Jan 21 '13
I'm not sure you understand what I'm saying, because it has nothing to do with optimization.
While a compile time constant value of 0 can be used to represent a null pointer, there is no requirement that the run-time value of a null pointer is 0, therefore,
There is no guarantee that dereferencing a null pointer results in an attempt to access address 0, therefore,
There is no guarantee whatsoever that dereferencing a null point will result in a crash.
It all goes back to what I said originally - there is a lot of behavior in C and C++ that coders assume is standard and well defined, when in reality it is undefined behavior that just happens to have similar implementations in most of the common compilers.
-1
u/NYKevin Jan 21 '13
Having
NULLtranslate to a legal (within the process's space) address is completely insane, however, so it's incredibly unlikely, in practice. It might be nonzero for some bizarre reason, but it's not going to be legal unless the compiler designers are smoking crack.1
u/seventeenletters Feb 19 '13
a huge amount of C code runs on devices where
a) it is the only program on the hardware and
b) it has full access and control of all memory locations, including the memory at pointer location 0
2
u/shustrik Jan 21 '13
I understand the concept, but not what the author applies it to. How is creating an invalid pointer an undefined operation in C? Does the standard allow the compiler to treat the pointers in a different way than other data types, say, signed int?
1
u/seventeenletters Feb 19 '13
It literally allows the compiler to do anything. That is how "undefined behavior" is defined in the standard. Return 0, do nothing, exit, write random bytes into a random location, whatever.
And furthermore, unlike "implementation dependent" behavior, the compiler authors do not even have to provide documentation regarding which behavior may occur.
1
Jan 26 '13
Well then, almost all C and C++ programmers aren't future proof. If it's undefined in the standard, don't use it. How hard can it be to adhere to this really simple rule?
1
u/minno Might know what he's talking about | Crypto Jan 26 '13
I think the author's point is that even pieces of software that are generally regarded as well-written use undefined behavior all the time, so it's unrealistic to expect anyone to avoid it.
1
Jan 26 '13
I think we (me and the author) have different definitions of well-written. If something is well written, then it conforms to the standard and makes no use of undefined behaviour. We have standards for a reason.
The author's point is really to keep the programmer from doing stupid things. The languages don't. What should keep the programmer from doing stupid things is the programmer himself, for if he is a good programmer he will know the consequences.
2
u/Nebu Jan 21 '13
The compilers are (trying) to adhere to the standard, so ignoring things like bugs in the compiler, the problem isn't with the compilers.
The problem is that programmers are writing code which produce undefined behaviour.
The author lists 4 possible solutions, one of which involves changing the language standards (e.g. to reduce the amount of undefined behaviour).
11
u/ponchedeburro Jan 21 '13
We ditch the C and C++, and port our systems code to Objective Ruby or Haskell++ or whatever.
Yeah, let's pick something obscure to use instead.
17
0
u/mgrandi Jan 21 '13
Objective-ruby made me laugh. But in all honesty, objc is nice and makes c at least bearable
3
u/zzing Jan 21 '13
One thing I have not seen mentioned is that ignorance will lead to undefined usages. The standard is a rather large tome, so a nice list of things not to do would be helpful in this regard.
6
u/lordlicorice Jan 21 '13
many people expect that creating an invalid pointer (but, again, not dereferencing it) is harmless.
I'd be interested in seeing what part of the standard forbids creating null pointers.
28
Jan 21 '13
Just to elaborate, NULL pointers are valid pointer values. Dereferencing a NULL pointer is undefined behavior, yes, but it is still a valid pointer value.
However, an uninitialized pointer will have an invalid pointer value, so will a pointer that has been deallocated using free. As such the following is undefined behavior:
int* x; int* y; x = y; // Undefined behaviorThis is also undefined behavior:
void f(int* p) {} int* x; f(x); // Undefined behaviorUndefined behavior really means the compiler is free to do whatever it wants. For an example of something unintuitive consider the following code:
bool x; if(x) { printf("true"); } if(!x) { printf("false"); }You might think that since x is a bool, even if it's uninitialized it can only be either true or false, but actually GCC can treat it as being both simultaneously or it can be neither simultaneously! Depending on the compiler version and optimization flags, GCC will produce code that prints both true AND false, in effect it gets rid of the if statement's check. Or it can produce an executable that prints neither true or false, in effect it optimizes out the entire if statement and its body. Or it can produce an executable to prints one or the other. Technically it can do whatever it wants given that performing a read operation on an uninitialized variable is undefined behavior.
1
u/lovelydayfora Jan 21 '13
I don't believe a freed pointer would be invalid. Nothing forces you to use malloc/free. If you manage your memory yourself you just need sbrk.
6
u/TheCoelacanth Jan 21 '13
sbrk is not standard C; it's an extension to the standard library. A freed pointer is invalid in standard C, but some compilers/standard libraries may let you use use one without ill effects.
The first example, while undefined in standard C, will not have any unusual effects with a typical compiler as long as you don't rely on x or y having any specific value. However, on some rare architectures that can trap on certain values, it may cause an error to be raised.
9
u/nomad42184 Jan 21 '13
He's not talking about null pointers. Null pointers are valid and initialized pointer with well-defined semantics (though, clearly, the can't be dreferenced). What he's talking about is creating a pointer that wasn't obtained or initialized in a valid way (e.g. creating a new pointer with initializing to the address of a valid variable or to a null pointer).
-5
u/lordlicorice Jan 21 '13
Null pointers are valid and initialized pointer with well-defined semantics (though, clearly, the can't be dreferenced)
You could say that about any pointer. "This pointer is valid and has well defined semantics.... as long as you never use it."
14
u/nomad42184 Jan 21 '13
No, actually; that's the point he's making in the article. Creating an invalid pointer (i.e. a pointer that doesn't point to a valid variable address or isn't a null pointer) does not have well defined semantics . . . it's undefined behavior, and the compiler may do whatever it pleases with the implicated code, even if you never use the pointer.
2
u/shustrik Jan 21 '13
What does the standard permit to do with pointers that is any different than, say, integers? I'm not intricately familiar with the C/C++ standards, but author's claim sounds to me like "the standard doesn't say anything about what happens when I assign 42 to a variable, so that behaviour is undefined, and is dangerous."
2
u/zokier Jan 21 '13 edited Jan 21 '13
Afaik (and I'm not a language lawyer) the concept of "undefined behavior" is well defined in the standard.
edit: neat, CERT has a list of all C undefined behavior. That should clarify things a bit.
2
u/moor-GAYZ Jan 21 '13
The standard clearly says that pointer arithmetic is defined only within one allocation unit (a block returned by
mallocor various kinds of statically/stack allocated structures or arrays, with the possibility of padding). Curiously enough that allows for making a standard-compliant C implementation that is impervious to any kind of buffer overflows.As for why undefined behaviour is dangerous: here's an actual linux kernel exploit.
1
u/TheCoelacanth Jan 21 '13
The standard permits anything to happen with non-NULL pointers that don't point to a valid object or to one past the end of a valid object. For instance, in this situation:
char arr[10]; char *x = arr+11;the compiler is permitted to raise an error because x points outside of the bounds of arr.
1
u/thisotherfuckingguy Jan 21 '13
char *ptr1 = 0xFFFFFFFFF; char *ptr2 = "Test"; if(ptr1 > ptr2){ ... } if(ptr1 < ptr2){ ... }The pointers don't dereference, but the pointer is still invalid and so the compiler may do whatever it sees fit with regard to the if-statements because it know the comparison is undefined. Probably what will happen is that it eliminates both of them, keeps one of them or evaluates them both.
Note, however, that there is nothing wrong with the pointer comparison when used like (for example) this:
char *ptr1 = "Test"; char *ptr2 = &ptr[2]; if(ptr1 > ptr2){ ... } if(ptr1 < ptr2){ ... }
1
u/moor-GAYZ Jan 21 '13
Option 5: compilers that weren't purposefully written in backward ways to thwart proprietary tool writers warn about more and more undefined behaviour that was exploited during optimization (and allow nice warning-suppression options). Clang is doing OK in that respect, for example.
0
Jan 21 '13
[deleted]
3
u/nomad42184 Jan 22 '13
Option 1 was clearly a joke on the author's part. 'Objective Ruby' and 'haskell++' aren't even real languages, and even their names sound like they're meant to evoke the notion of the oft promised but never delivered panacea languages.
2
9
u/samvdb Jan 21 '13
If you look at the lines of code that caused the problem in zlib, you see that it's caused by the developers trying to do micro-optimizations. With macro's. This code was wrong in more ways than just the undefined behavior.