by first_amendment · 9y ago · 0 comments
If you want to make sure your callers are obeying the interface contract, use assert() to not incur runtime overhead in production and guard against programming error:
int add(int a, int b) {
assert(!__builtin_sadd_overflow(a, b, NULL));
return a + b;
}This is incorrect.
"Undefined behavior" is a specific technical term for a scenario in a program that the compiler is permitted by the specification to assume will not happen, for the purposes of optimization. For instance, this code:
int silly(int a) {
if (a + 5 > a) return 0;
return 1;
}
can be optimized to just "return 0", because, as a human would read it, obviously a + 5 > a. So the spec says that signed integer overflow cannot occur to allow the compiler to optimize this as a human would want the compiler to optimize this. (Whether the spec actually matches human expectations is a good question, but in general it's right, and forbidding all undefined behavior in C and C++ would cause you to miss out on tons of optimizations that you obviously want.)"Undefined behavior" does not mean providing invalid input to a function and getting an exception, or a crash, or a particular error result, if the result is well-defined. For instance, this is defined behavior:
>>> import math
>>> math.sqrt(-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error
because Python defines the behavior that math.sqrt(-1) raises a ValueError and I can reliably catch that exception. If it were undefined behavior, then I wouldn't have any guarantee of being able to catch the ValueError: the Python interpreter might just choose to return 27 if it's more convenient.Python's philosophy of giving well-defined behavior to meaningless code seems wasteful. If your code is unintentionally executing sqrt(-1) (or unintentionally indexing out of bounds, etc) then something is wrong with your program. You don't necessarily need the behavior to be defined if there is a bug in your program. In the case that you want something predictable to happen, better to just abort(). Catching ValueError/IndexError in those cases is futile, how can one trust a buggy program to handle itself?
Python using exceptions to signal both runtime errors and programmer errors is a design smell. The former should always be caught and handled, the latter should never be caught and should probably only reasonably abort().
This is not Python's design. You might dislike Python's design, sure (many people do!), but it is recommended Python practice to try to do something, catch the well-defined exception, and implement the fallback rather than to check in advance.
https://docs.python.org/3.5/glossary.html#term-eafp
https://blogs.msdn.microsoft.com/pythonengineering/2016/06/2...
> Catching ValueError/IndexError in those cases is futile, how can one trust a buggy program to handle itself?
The program is not buggy.
(Also, it's absolutely possible to design software where bugs are contained to part of the code: for instance, if you hit a bug in your Python code while handling a web request, you should return a 500 to that user and carry on instead of aborting the whole web server. In fact, it is precisely the relative lack of undefined behavior in Python that makes this a good approach: if you were doing this in C, a wild pointer could well corrupt some other server thread!)
I'm arguing that an unintentional or unexpected ValueError, IndexError, TypeError, etc. means your program is buggy and there is no sane/practical way to 100% safely recover from it outside of restarting the process.
Your example of the catch-all handler in a modular HTTP server is inappropriate and dangerous. Continuing to run a server with persistent in-process state after an unexpected exception risks corrupting data. Just because Python doesn't have C pointers doesn't mean it can't have inconsistent or incorrect state that can affect other server threads.
The code has a well-defined meaning, it's just that the input domain is larger than the one defined in C.
This is the fundamental difference that makes C/C++ unsafe programming languages.
(Yeah, this specific case of the exported add funciton is unlikely to be too apocalyptic, but the general guarantees are important).
Sorry but sounds like you are not familiar with the special meaning of the term "undefined behaviour" in context of C/C++. It means your program may crash or corrupt memory in a way that results in remote code execution. (Or anything else... http://catb.org/jargon/html/N/nasal-demons.html )
In practice, for the addition function above, the convenient thing for any compiler on any reasonable platform is to just let the hardware handle overflow the way the hardware wants to. Signed overflow is undefined so that C as a language is portable to hardware with different ways of overflowing signed integers, and so there isn't a need for a compiler on one platform to implement special behavior. But it's unlikely to crash, corrupt memory, conjure demons, etc.
Corrupting memory requires a bit more setup: you do a bounds-check on a pointer in a way that hits signed overflow (or you do some inappropriate casts, or something), you get a result, and you use that result to index into an array. If the way that you got that result involved UB, your bounds check may not be valid. Again, this isn't because the compiler particularly desires to access invalid memory, but because it wants to do the cheapest possible thing that is still correct for all defined behavior.
I'm a huge fan of assertions and use them to document 'programmer screwed up' and to get notified of cases when that happens; I find that a more corect description then 'guarding against'. However we leave assertions on in release builds as well: tracking down cases of UB only happening in release builds (most often due to someone forgetting to initialize something) is hard enough already, and we found that leaving assertions on can help with that. Only in certain hot paths which prove the runtime overhead matters (and there's really not a lot of those) we'll turn them off.
Really? Why? And can you give an example of that in, say, Python?
Syntactically correct. Will provoke error during runtime due to invalid semantics.
But I was answering this specific to the question of "syntactically valid yet semantically invalid statements" in python.
(-1) ** 0.5
Why define something that has no meaning? Just a waste of cycles, CPU and brain. >>> (-1) ** 0.5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: negative number cannot be raised to a fractional power
Any conforming implementation of Python 2.7 must raise ValueError. Why define it? So that a programmer can catch ValueError.