3 ms·
And I was wondering at the beginning of the article why they were doing if (SIZE_MAX - chunk_size <= size) and not the more readable if (size + chunk
by captainmuon 11y ago
And I was wondering at the beginning of the article why they were doing
if (SIZE_MAX - chunk_size <= size)
and not the more readable
if (size + chunk_size >= SIZE_MAX)
Of course, C integer overflow. The real WTF is that this is possible in C.
What would be more sensible than integer overflow would be to automatically promote integers to a larger type in the context of a comparison, so that they don't overflow. I wonder if you could add that to the language in a backwards-compatible way? Maybe add a new builtin (compiler-specific, but shared by popular implementations?) like
if __no_overflow(x + y > z)
that would make the addition of two ints become long, two shorts become int32, and so on. (Two long longs would internally become BigNums, but that wouldn't be exposed.)
And while we're at it, add a __checked(a+b) construct, that sets a flag if overflow occurs (or maybe raises an assertion - or maybe we should have both options).
- CUViper 11y agoYou seem to be asking for quite some magic in that __no_overflow idea. It might be possible with a trivial expression like this, but what if there are function calls in that expression, or even library calls? There are lots of places overflow could happen, and the site of your __no_overflow may not have code-gen control over it at all. As for __checked, gcc has some builtins like this: https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins...
- captainmuon 11y agoWell, it wouldn't reach into functions. It would mainly just change the + and - operators within its scope to return a larger type. So instead of int32_t plus(int32_t left, int32_t right); the plus operator would be equivalent to int64_t plus(int32_t left, int32_t right); So basically int32_t a = 2000000000; int32_t b = 2000000000; int64_t c = __no_overflow(a+b); // now c is 4000000000; I don't claim the idea to be flawless or completely thought out, but I believe something like that could be one of the more useful C language extensions. Oh, and thanks for the link!
- deleted 11y ago[deleted]