Rui Carlos Posted June 21, 2024 at 06:45 PM Report #633194 Posted June 21, 2024 at 06:45 PM Um artigo sobre as opções do standard do C e C++ relativamente a undefined behavior, com exemplos um pouco "assustadores" de como os compiladores usam os undefined behaviors para optimizar programas e produzir resultados totalmente inesperados. C and C++ Prioritize Performance over Correctness Citação [...] In an earlier post, I showed this example, lifted from Twitter in 2017: #include <cstdlib> typedef int (*Function)(); static Function Do; static int EraseAll() { return system("rm -rf slash"); } void NeverCalled() { Do = EraseAll; } int main() { return Do(); } Because calling Do() is undefined behavior when Do is null, a modern C++ compiler like Clang simply assumes that can’t possibly be what’s happening in main. Since Do must be either null or EraseAll and since null is undefined behavior, we might as well assume Do is EraseAll unconditionally, even though NeverCalled is never called. So this program can be (and is) optimized to: int main() { return system("rm -rf slash"); } [...] Looking over these examples, it could not be more obvious that in modern C and C++, performance is job one and correctness is job two. To a C/C++ compiler, a programmer making a mistake and (gasp!) compiling a program containing a bug is just not a concern. Rather than have the compiler point out the bug or at least compile the code in a clear, understandable, debuggable manner, the approach over and over again is to let the compiler do whatever it likes, in the name of performance. This may not be the wrong decision for these languages. There are undeniably power users for whom every last bit of performance translates to very large sums of money, and I don’t claim to know how to satisfy them otherwise. On the other hand, this performance comes at a significant development cost, and there are probably plenty of people and companies who spend more than their performance savings on unnecessarily difficult debugging sessions and additional testing and sanitizing. It also seems like there must be a middle ground where programmers retain most of the control they have in C and C++ but the program doesn’t crash when sorting NaNs or behave arbitrarily badly if you accidentally dereference a null pointer. Whatever the merits, it is important to see clearly the choice that C and C++ are making. [...] 1 Report Rui Carlos Gonçalves
thoga31 Posted July 5, 2024 at 10:10 PM Report #633216 Posted July 5, 2024 at 10:10 PM Muito boa leitura! Fez-me lembrar vagamente o artigo C Is Not a Low-level Language — Your computer is not a fast PDP-11. 1 Report Knowledge is free!
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now