Where is the second overflow in this piece of code

Here is the code snippet from the GNU C Pg 74 reference:

If your code uses the index of a signed cycle, make sure that the index cannot overflow, as well as all signed expressions derived from the index. Here is a contrived example of problematic code with two examples of Overflow.

for( i = INT_MAX - 10 ; i <= INT_MAX; i++) if( i+1 < 0 ) //first overflow { report_overflow(); break; } 

Due to two overflows, the compiler may optimize or convert the two comparisons in a way that is incompatible with the wraparound assumption.

+6
source share
3 answers

What the GNU C Reference Guide means that you have two possible overflows. The first is the i++ operator in

 for( i = INT_MAX - 10 ; i <= INT_MAX; i++) 

and the second - i+1 in

 if( i+1 < 0 ) //first overflow 

C code example eliminates perpetual loop with

 if( i+1 < 0 ) //first overflow { report_overflow(); break; } 

and for that you rely on wrapparound signed behavior.

However, in Appendix A.3, you are informed that you should not rely on the signed wraparound behavior because the optimizer uses its undefined behavior and can generate code that will behave differently than you expect. This refers to the if( i+1 < 0 ) code snippet, which is supposed to bypass when i equals INT_MAX .

As a conclusion to the above code may fail after optimization by the compiler.

+4
source

Convert from comment:

i <= INT_MAX always true, so the loop can never exit. So this is a mistake, because I overflow ++.

Since this is always true, the compiler can optimize this condition, which is clearly not as expected.

+2
source

due to a break, there should not be a single one without a break; it will be an eternal cycle and overflow in ++i
since i <= INT_MAX true for all values โ€‹โ€‹of i (if i is an integer)

+2
source

Source: https://habr.com/ru/post/972638/


All Articles