by devrandomguy · 9y ago · 0 comments
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
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?
"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.
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.
It's been a valid concern for years. I'm not sure where you get "suddenly" from.
And where do you think the people writing NASA or Tesla code tomorrow are learning code from today?
I'm getting it from the inanity of pointing it out in a sample C++ code in a post announcing a new FFI lib.
It's something people can write 100000 line programs and rarely care about to check. So quite far from the first concern that one should have when writing a sample 2 line function to showcase an FFI helper.
In other words, it's as relevant as someone saying 1+1=2 casually and someone pointing out in all pomposity that "actually the representation depends on the base of the number system, in binary it would be 1+1=10".
Man, these languages are seriously !!fun!!
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;
}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.
If not (and you are providing a general purpose addition), then you need a big number library.
CL-USER> (sqrt -1)
#C(0.0 1.0)