4 ms·
In the vast majority of cases, integer overflow or truncation when casting is a bug, regardless whether it is undefined, implementation-defined or well-defined
by nwellnhof 2y ago
In the vast majority of cases, integer overflow or truncation when casting is a bug, regardless whether it is undefined, implementation-defined or well-defined behavior. Avoiding undefined behavior doesn't buy you anything.
If you start to fuzz test with UBSan and -fsanitize=integer, you will realize that the choice of integer types doesn't matter much. Unsigned types have the benefit that overflowing the left end of the allowed range (zero) has a much better chance of being detected.
- gavinhoward 2y ago> Avoiding undefined behavior doesn't buy you anything. This is absolutely false. Say you want to check if a mathematical operation will overflow. How do you do it with signed types? Answer: you can't. The compiler will delete any form of check you make because it's UB. (There might be really clever forms that avoid UB, but I haven't found them.) The problem with UB isn't UB, it's the compiler. If the compilers didn't take advantage of UB, then you would be right, but they do, so you're wrong. However, what if you did that same check with unsigned types? The compiler has to allow it. Even more importantly, you can implement crashes on overflow if you wish, to find those bugs, and I have done so. You can also implement it so the operation returns a bit saying whether it overflowed or not. You can't do that with signed types. > If you start to fuzz test with UBSan and -fsanitize=integer, you will realize that the choice of integer types doesn't matter much. I do this, and this is exactly why I think it matters. Every time they report UB is a chance for the compiler to maliciously destroy your hard work.
- nwellnhof 2y ago> You can't do that with signed types. What? Of course you can. If you want to add ints a and b: if (b >= 0 ? a > INT_MAX - b : a < INT_MIN - b) printf("overflow\n");
- gavinhoward 2y agoOkay, that's addition. Now do it for multiplication.
- lelanthran 2y ago> In the vast majority of cases, integer overflow or truncation when casting is a bug, regardless whether it is undefined, implementation-defined or well-defined behavior. Avoiding undefined behavior doesn't buy you anything. With respect, this is nonsense. With UB, the compiler might remove the line of code entirely. With overflow/underflow/truncation, the results are well-defined and the compiler is not allowed to simply remove the offending line.