3 ms·
That's not true at all. Compilers can detect some instances of UB, and they will happily warn when they do. Most instances of UB are ones that the compiler co
by foxfluff 5y ago
That's not true at all. Compilers can detect some instances of UB, and they will happily warn when they do.
Most instances of UB are ones that the compiler could not detect. Your compiler isn't going to detect that your integer overflows, it assumes that it won't. Shit blows up if that assumption was wrong.
If you want to detect UB, you should run ubsan and the like. The compiler is not running it.
- GoblinSlayer 5y agoIt blows up, but not as violently as when the compiler adds fuel to it.
- jerf 5y agoIn some sense, the problem isn't that the compiler "can't" detect that an integer addition will overflow. The problem is that with some exceptions (a loop that is clearly indexing along an array, for example), the compiler will have to flag every integer addition as UB. UB notifications aren't that useful if you're getting a dozen for every five line function in your entire codebase. Programmers do not, in general, want to do the amount of work it takes to safely add two numbers together. You need something "weird". Like an error path for every addition. Or a type system for ranges, where you actually have to specify ranges (because adding two bytes together that you casually left as 0-255 will create a new ranged value 0-510; multiplication is even more fun). Or some other exotic idea. So we just let them overflow and the chips fall where they may.
- foxfluff 5y ago> In some sense, the problem isn't that the compiler "can't" detect that an integer addition will overflow. It absolutely can't if it doesn't know what the values are going to be. > the compiler will have to flag every integer addition as UB No, I disagree. If it has no knowledge of my runtime values, it can't flag addition as UB because it isn't. It's UB only if I'm using values that would overflow, and the compiler in general can't know that. If I've done my program right, it will never overflow. There is no UB, any flag would be just absolutely wrong. The compiler couldn't detect UB. There's nothing to flag. If it knows the values, then of course it can detect it and flag it: x.c:3:18: warning: integer overflow in expression of type ‘int’ results in ‘-2’ [-Woverflow] 3 | int a=2147483647+2147483647; > Programmers do not, in general, want to do the amount of work it takes to safely add two numbers together. I agree that overflow-checking is needlessly sucky in C but that's not "the problem." I usually make sure my arithmetic is safe but the compiler won't know it.