for every int x: x+1 > x … is this always true?

后端 未结 4 1903
鱼传尺愫
鱼传尺愫 2021-01-18 00:27

I\'m just starting to learn C at school, I\'m trying to get a hold of the basic concepts.

Our homework has a question,

for every int x: x+1 > x

4条回答
  •  不思量自难忘°
    2021-01-18 00:59

    x + 1 > x
    

    is 1 for every int value except for value INT_MAX where INT_MAX + 1 is an overflow and therefore x + 1 > x expression is undefined behavior for x value of INT_MAX.

    This actually means a compiler has the right to optimize out the expression:

    x + 1 > x
    

    by

    1
    

    As INT_MAX + 1 is undefined behavior, the compiler has the right to say that for this specific > expression INT_MAX + 1 is > INT_MAX.

    As the x + 1 > x expression is undefined behavior for x == INT_MAX, it is also not safe to assume x + 1 > x can be false (0).

    Note that if x was declared as an unsigned int instead of an int the situation is completely different. unsigned int operands never overflow (they wrap around): UINT_MAX + 1 == 0 and therefore x + 1 > x is 0 for x == UINT_MAX and 1 for all the other x values.

    Modern compilers (like gcc) usually take the opportunity to optimize this expression and replace it with 1.

    For the record, there was some serious security issues with known server programs using code like:

     if (ptr + offset < ptr)
    

    The code was meant to trigger a safety condition but the compiler would optimize out the if statement (by replacing the expression with 0) and it allowed an attacker to gain privilege escalation in the server program (by opening the possibility of an exploitable buffer overflow if I remember correctly).

提交回复
热议问题