3 ms·
Best I can tell is that overflow is undefined behavior for signed ints in C/C++ so -O3 with gcc might remove a check that could only be true if UB occurred. Th
by appellations 1y ago
Best I can tell is that overflow is undefined behavior for signed ints in C/C++ so -O3 with gcc might remove a check that could only be true if UB occurred.
The compound predicate in my example above coupled with the fact that the compiler doesn’t reason about the precondition in the prior assert (y is non-negative) means this specific example wouldn’t be optimized away, but bluGill does have a point.
An example of an assert that might be optimized away:
int addFive(int x) {
int y = x + 5;
assert(y >= x);
return y;
}
- comex 1y agoClang is a bit smarter than GCC here (for some definition of 'smart') and does optimize the original version: https://gcc.godbolt.org/z/3Y4aheG6x https://gcc.godbolt.org/z/3Y4aheG6x
- uecker 1y agoYes, you can not meaningfully assert anything after UB in C/C++. But you can let the compiler add the trap for overflow -fsanitize=signed-integer-overflow -sanitize-trap=all, or you could also write your assertion in a way where it does not rely on the result (e.g. ckd_add), or you use "volatile" to write in a way the compiler is not allowed to assume anything.