8 ms·
A Guide to Undefined Behavior in C and C++ (2010)
- kstenerud 8y agoAnd therein lies a major problem with c and c++ compilers: It's effectively impossible to write bug free code. Bugs in c and c++ usually trigger undefined behavior. It is therefore impossible to write a conforming program, which makes any guarantees in the spec meaningless. I've hit heisenbugs like these that only trigger when optimized, and resist write(), out(), fflush(), etc and it's infuriating. Or even worse: programs that no longer work when compiled on a newer compiler. With other languages, you are at least spared from this kind of code decay. But everyone's writing compilers to the spec so tough :/
- nwmcsween 8y agoThat's actually good your code breaks using new compilers as it means the code is bogus anyways. The alternatives to UB is either a strict spec that will be dog slow on $arch or abstract away everything and make it complex.
- saagarjha 8y agoThis isn't necessarily true. Many compiled languages these days have a strong specification that guarantees a lack of undefined behavior for the vast majority of code, yet remain relatively performant–think Swift, Rust, and the like.
- pjmlp 8y agoBeing dog slow is very much dependent on the use case. Yes it will be slower than taking every shortcut in the name of performance. What really matters is, does the execution speed and memory footprint meat the requirements? If the user is happy to get their data in 100ms, with a requirement of 300ms max, getting it in 10ms is hardly an advantage.
- jjnoakes 8y agoIf you can deliver responses 10x faster than required, you can scale with 10x fewer resources (or at least presumably some factor of fewer resources) and still stay within the user requirements. I'd say that's a nice advantage.
- pjmlp 8y agoNot everyone is going to be the next Google, Facebook, Crytech, EA, ... There are better ways to waste money than spending it on YAGNI features.
- jstimpfle 8y agoConsider Parkinson's law... Compare git to mercurial... Consider how many successful Java command line programs are there?
- pjmlp 8y agoThere are plenty of them at the enterprise level. Just a couple of months ago I re-wrote several Korn shell scripts doing ETL related tasks into a couple of saner Java CLI programs at customer request.
- jstimpfle 8y agoAnd the responsiveness is good? Isn't there always this terrible startup lag? Could we rewrite the C implementation of e.g. git in Java to get a program that is just as fast (e.g., instantaneous response for most operations)?
- pjmlp 8y agoSurely, you know that there are native code compilers for Java, right?
- 8y ago
- banachtarski 8y agoThis is a myopic viewpoint. Undefined behavior is critical for code that needs to be fast. The premise of languages like C and C++ is that the airgap between the language's abstract execution and memory model and the hardware's is thin to non-existent. *(edit accidentally submitted early) In this case, the UB is due to the compiler's ability to reorder statements. This is such a fundamental optimization that I can't imagine you're really suggesting that a language without this optimization capability is a "problem." Rearranging instructions is critical for pretty much any superscalar processor (which all the major ones are), and I hate to imagine the hell I'd be in if I had to figure out the optimal load/store ordering myself.
- saagarjha 8y ago> In this case, the UB is due to the compiler's ability to reorder statements. No, the undefined behavior arises because dividing by zero is undefined. Languages wishing avoiding this particular bug can make division by zero defined to trap or have some sort of guaranteed behavior, after which the compiler is required to not reorder those statements. In this case reordering the instructions is legal because having undefined behavior in your program makes literally anything the compiler does legal.
- banachtarski 8y agoMy point still stands in that I don't want the compiler to check for division by zero if I don't ask it to.
- saagarjha 8y agoSure, then use C or C++ and check for it yourself. But if you mess up your program is invalid, so there's that. If you don't like that, write your own assembly by hand to convert this to implementation-defined behavior instead of undefined behavior.
- deleted 8y ago[deleted]
- 8y ago
- otabdeveloper2 8y ago"Undefined behavior" doesn't mean "buggy". It simply means stuff that's CPU-specific or compiler-specific. C++ has a standard, unlike languages like Rust or Python. This is a good thing, because compiler-specific crap doesn't magically go away if you avoid standards and just declare one implementation as a "reference".
- saagarjha 8y ago> "Undefined behavior" doesn't mean "buggy". It simply means stuff that's CPU-specific or compiler-specific. Yes, it does. The behavior you are describing is "implementation specific", and it is ok to have this in your program provided you know what your implementation will do. It is illegal to have any undefined behavior in a well-formed C/C++ program.
- otabdeveloper2 8y agoWhen people talk of UB in C++ they always mean "implementation specific".
- saagarjha 8y agoNo, they don’t. These are separate concepts with different behavior. “Undefined behavior” is illegal to have in C/C++ programs and includes things like division by zero and out-of-bounds array access. “Implementation specific” behavior is legal but allowed to differ, such as querying the size of an int.
- esrauch 8y agoYou really don't need to go very far to get into UB instead of implementation defined: signed int overflow is already UB and the program is permitted to do literally anything if you ever accidentally make one of your ints too large.
- tom_ 8y agoThe standard doesn't defined well-formedness, nor does it consider undefined behaviour illegal necessarily. It simply has nothing to say about what happens when undefined behaviour is invoked. And it is OK to invoke it if you know what your implementation will do. The standard even gives documenting the behaviour as an option. (I wonder how many people worry about supplying clang a file that doesn't end in a new line? That is undefined behaviour, and yet you know exactly what's going to happen: you'll get a warning, if compilation continues the code will build as if the new line were there, and clang won't delete your source file, even though it would be perfectly within its rights to.)
- shin_lao 8y ago| It's effectively impossible to write bug free code. What does that even mean? It's impossible to have bug free code in any language. Bug in the libraries, the compiler, in the OS, in the hardware...
- ilovecaching 8y agoThis is why if you're currently writing C or C++, please, please look into Rust. Titus Winters just did a great talk at Pacific++ outlining how difficult it is to understand the quirks of C++. Not even Bjarn can keep all of it in his head. The dice are completely loaded against you to fail and introduce bugs, unintended behavior, and vulnerabilities in your code. Rust isn't a silver bullet that will suddenly fix your life, but it doesn't deal with the crazyness of C undefined behavior and doesn't have to be backwards compatible. It's designed from the ground up to make comprehensive sense, and safety is a feature enforced for you by the compiler in many cases.
- banachtarski 8y ago> This is why if you're currently writing C or C++, please, please look into Rust. Ugh if you read the article, you would know that the UB described here is the same in Rust. There is this massive group think about which languages are safe and/or fast, and whenever an article like this comes up, invariably someone says "Rust!" without really looking at the problem itself. Personally, I am in wait and see mode on Rust. Without better generics support (aka template <size_t> or similar) and a number of other things, it still doesn't meet my bar for writing fast generic code, and who knows how complex it will be at that point? I say the jury is still out.
- red75prime 8y agoUB is a way to better optimize code by (silently) offloading a burden of correctness proof to a programmer. Rust prefers to be more explicit about it. Const generics will surely not change that.
- saagarjha 8y ago> Ugh if you read the article, you would know that the UB described here is the same in Rust. There is this massive group think about which languages are safe and/or fast, and whenever an article like this comes up, invariably someone says "Rust!" without really looking at the problem itself. Rust does have vocal proponents, but I don't see how "the UB described here is the same in Rust". Rust should trap consistently when dividing by zero.
- anderskaseorg 8y ago(2010)
- duneroadrunner 8y agoYeah, with modern C++, you can largely choose to avoid using elements that are prone to undefined behavior. For example, rather than native integers, you could use a compatible integer class that checks for division by zero [1]. Or one that checks for overflow too [2]. The Core Guidelines lifetime checker aims to (eventually) make native pointers and references memory safe via (severe, but not quite as severe as Rust) usage restrictions. And when you need to circumvent the restrictions, you can use an unrestricted smart pointer with run-time checking [3][4]. [1] shameless plug: https://github.com/duneroadrunner/SaferCPlusPlus#primitives https://github.com/duneroadrunner/SaferCPlusPlus#primitives [2] https://github.com/boostorg/safe_numerics https://github.com/boostorg/safe_numerics [3] https://github.com/duneroadrunner/SaferCPlusPlus#registered-pointers https://github.com/duneroadrunner/SaferCPlusPlus#registered-... [4] https://github.com/duneroadrunner/SaferCPlusPlus#norad-pointers https://github.com/duneroadrunner/SaferCPlusPlus#norad-point...
- pjmlp 8y agoI agree, the problem is ensuring everyone at the company and third party dependencies, many of which available as binary libs only, do actually use those modern C++ constructs.
- the_why_of_y 8y agoInteresting project; are you aware of any actual users? Meanwhile, in the real world, C++ programmers typically use operator+(int,int) with UB on overflow because it's conveniently built into the language. The problem with C++ isn't that doing the right thing is impossible, it's that doing the wrong thing is the default, with no dependencies and no syntactic overhead.
- jcelerier 8y ago> Meanwhile, in the real world, C++ programmers typically use operator+(int,int) with UB on overflow because it's conveniently built into the language. In more than a decade of coding with C++ I have never been bitten by a signed overflow bug which is UB. However I have been hit by unsigned underflow (e.g. if(2u - 3u > whatever)) way too often even though it is perfectly "legal" from the point of view of the language.
- banachtarski 8y agoFor those viewing this thread, one year after this article was written, this was standardized: https://en.cppreference.com/w/cpp/numeric/fenv https://en.cppreference.com/w/cpp/numeric/fenv