15 ms·
I like how the first basic example invokes undefined behaviour without mention: int add(int i, int j) { return i + j; }
by fulafel 9y ago
I like how the first basic example invokes undefined behaviour without mention:
int add(int i, int j) {
return i + j;
}
- deleted 9y ago[deleted]
- devrandomguy 9y agoLooks fine to me. Are you supposed to check for integer overflow before doing the addition, or something?
- nikbackm 9y agoProbably. Signed integer overflow is undefined behaviour in C and C++.
- first_amendment 9y agoSo is sqrt(-1) but that doesn't mean sqrt() shouldn't exist. Just don't call add() with arguments that will overflow.
- devrandomguy 9y agoSo, sanitize your `/add?a=1&b=2` endpoint inputs by making sure that they don't add up to something greater than... wait a sec. Actually, let's just return an unsigned int. No wait! We might get a negative number as input. Hmm, can I bitbang my way out of this? Can I be sure that the signed ints are two's complement? Man, these languages are seriously !!fun!!
- first_amendment 9y agoThere will always be syntactically valid yet semantically invalid statements in any grammar. Undefined behavior isn't bad, it's a unavoidable consequence of all languages, programming or otherwise. Grammatical constructions that have no meaning will always exist. 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; }
- icebraining 9y agoThere will always be syntactically valid yet semantically invalid statements in any grammar. Really? Why? And can you give an example of that in, say, Python?
- first_amendment 9y ago(-1) ** 0.5 Why define something that has no meaning? Just a waste of cycles, CPU and brain.
- pavanky 9y agoI am assuming this is python. This fails in python2 but works (returns complex number) in python3.
- geofft 9y agoThis is well-defined: >>> (-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.
- first_amendment 9y agoAs I said in another thread, trusting a buggy program to debug itself is futile. Effectively handling unintentional ValueError (or IndexError, TypeError) is not practically possible. For one, there's a good chance the program's persistent shared state is in an inconsistent state when those unintentional exceptions happen. Better to just abort().
- striking 9y agoThey can choose to do just that. But they're also afforded a little more flexibility with this approach. A developer could use this to serve up a stack trace rather than just crashing the server, for example.
- a_t48 9y agoIt must be nice to live in a world where you don't need to write fast code.
- coldtea 9y agoSo, like what's the case for 99% of programmers?
- fulafel 9y agoSafe semantics don't preclude fast code. See eg Rust, which arguably enables you to write faster code than C++ - because its guarantees let you have confidence in correctness of complex programs involving fine grained shared memory parallelism mutating common data.
- richardwhiuk 9y agoIf you just specify that a < INT_MAX/2 and b < INT_MAX/2, you are fine. If not (and you are providing a general purpose addition), then you need a big number library.
- junke 9y agoYou can also overflow by adding two large enough negative numbers. /tmp/file.c:2:[kernel] warning: signed overflow. assert -2147483648 ≤ i+j; /tmp/file.c:2:[kernel] warning: signed overflow. assert i+j ≤ 2147483647; (tis-analyzer)
- geofft 9y agoSanitize your endpoint to ensure that both a and b are within INT_MIN/2 to INT_MAX/2. After all, you didn't pick INT_MIN; the entire point of a 32-bit integer or a 64-bit integer is that it's more than enough for reasonable purposes. It's not based on a physical constant or anything, it's just convenient and large. If you need a specific number of bits for your purposes that's more than that, use a u128 extension or a bigint type.
- deleted 9y ago[deleted]
- junke 9y agoCL-USER> (sqrt -1) #C(0.0 1.0)
- pjmlp 9y agoYep, add(INT64_MAX, 1) Is undefined. If using Ada, similar kind of code would produce "raised CONSTRAINT_ERROR : program.adb:7 overflow check failed" To be fair, Ada's behavior is easy to reproduce with a checked integer class like https://accu.org/index.php/journals/324 https://accu.org/index.php/journals/324
- coldtea 9y agoSo? There millions of lines of code, from the best C/C++ programmers, even the kernel, that add two ints in all kinds of programs. Why is this suddenly a valid concern, especially for a code example, not NASA's missile code or Tesla's self-driving libs?
- pjmlp 9y agoIt is not a sudden concern, it has been ignored since C and C++ exist, and only became worse with code exposed to the world via the Internet. "Many years later we asked our customers whether they wished us to provide an option to switch off these checks in the interests of efficiency on production runs. Unanimously, they urged us not to--they already knew how frequently subscript errors occur on production runs where failure to detect them could be disastrous. I note with fear and horror that even in 1980, language designers and users have not learned this lesson. In any respectable branch of engineering, failure to observe such elementary precautions would have long been against the law." -- Tony Hoare, "The 1980 ACM Turing Award Lecture" Millions of people also drive without security belt or helmet, apparently they are an useless extra.
- the_grouch 9y agoOne can do an overflow analysis of a whole program. This however takes time and would prevent frequent Hacker News comments. Do people who write such programs comment here? I don't think so.
- zurn 9y agoGoogle for "site:cvedetails.com integer overflow linux" Yeah, there are places in code like that, and many of those lines have been security vulnerabilities. For anyone who is surprised by this and is handling untrusted data in C/C++, it's a good idea to read up on the subject.
- coldtea 9y agoI like it how contrived complaints can get...
- aoloe 9y agowhat about opening a ticket / doing a pull request with a better trivial example that does not "teach" bad habits?
- geofft 9y agoA simple fix is using unsigned integers, as unsigned overflow is well-defined. (There isn't a way in C/C++ to request an exception or fault on integer overflow, which is what you'd want here, since you're running inside Python. A better conceptual fix is just doing the addition in Python, which is a more robust language than C/C++ for signed integer addition, but that kind of defeats the point of the example.)
- first_amendment 9y ago> There isn't a way in C/C++ to request an exception or fault on integer overflow This is incorrect. See compiler options: -ftrapv, -fsanitize=undefined. See compiler builtins: __builtin_add_overflow and friends.
- fulafel 9y agoBut no way in standard C/C++.
- deleted 9y ago[deleted]
- first_amendment 9y agoGCC/Clang/VC++ represent 99% of the compiler market. In the exceedingly rare chance your vendor doesn't implement those extensions, you're probably a big enough customer of theirs that you can request it.
- geofft 9y agoI mean, yes, I'm sympathetic to the argument that most people should use a variant of C that isn't actually C and is much better about undefined behavior (not just integer overflow but other things too). https://blog.regehr.org/archives/1180 https://blog.regehr.org/archives/1180 has some thoughts along these lines. I'm not sure that pybind11 wants to have its docs using a nonstandard variant of C, though, for lots of reasons, including that I expect the major use case of pybind11 is binding to existing C or C++ projects which are generally written in standard C or C++. (But not always! Postgres, for instance, is written in a variant of C with -fwrapv - not even -ftrapv, but a definition of signed overflow - instead of standard C.)
- louiz 9y agoJust like “operator+(int, int)” invokes undefined behaviour without mention: you can write “a + b” and it will break if the addition overflows! Or std::vector<T>::operator[] invokes undefined behaviour if the argument is invalid (out of band). Or printf() invokes undefined behaviour if an argument is of the wrong type (for example "%s" with a corresponding int). Or strcpy invokes undefined behaviour if you give it invalid pointers (or non-null terminated strings, etc). So, yeah, many functions can invoke undefined behaviour when they are called with bad arguments, that doesn’t make them bad functions.
- fulafel 9y agoThe difference is that this was a function exposed to Python. The expectation of Python programmers is that calling into the module won't explode. The Python vs C++ joke here is that the minimal a + b example turns out to be unsafe to call with random numbers.
- kazinator 9y agoA certain loss of safety is common when you're using FFI. Take any language's FFI and bind to the C library atoi function. Poof, you have instant undefined behavior for bad string to int conversions. If you want a safe, robust module that is based on FFI, you have to write some padding in the higher level language that avoids misusing the foreign API in any way. Directly exposed FFI stuff is not safe and cannot reasonably be safe; it makes no sense to expect that.
- fulafel 9y agoI disagree that this is a FFI. There's are FFIs for Python, the builtin one is called ctypes, and users know it's an exception to Python's safety. Modules implemented in C++ and presenting functionality to Python programs in a native way are expected to be safe.
- kazinator 9y agoUnless I'm mistaken, the topic is Pybind11, which is a foreign binding mechanism. Being criticized is the example in its documentation: http://pybind11.readthedocs.io/en/master/basics.html http://pybind11.readthedocs.io/en/master/basics.html under the heading "Creating bindings for a simple function". Looks like FFI to me.
- e12e 9y agoI for one am grateful for this comment, I program rarely enough in C/c++ that I wouldn't have assumed signed overflow was undefined. As the example below with "int a; a+5>a" illustrates, that's potentially pretty serious. I wonder if the "best" fix here, would be to use assembler intrinsics to maintain performance, possibly with a fallback to a type cast/promotion to a bigger int for the sum, and some form of defined behaviour for overflow on the python side? (reinventing the python number tower with full automatic promotion seems counter-productive here, as presumably the idea is to work with fast/simple/native (signed) integer math...) Or just redefine the function to use unsigned ints.