cinteger-overflowpost-increment

Does a variable holding result of signed integer overflow (side effect of post incr.) and, after that, never used it in any expression, result in UB?


Consider this program

#include <limits.h>

int main (void) {
    int i = 0;

    // Assume, user is a fair person, following the instruction strictly..
    printf ("Enter a number in the range [0 - INT_MAX] : \n"); 
    scanf ("%d", &i);

    while (i++ < INT_MAX) {
        // do some stuff..
        // value of variable i not used in loop body
    }

    // value of variable i is not used anywhere after loop body

    return 0;
}

In the last evaluation of loop condition i++ < INT_MAX, the value of i in the expression will be INT_MAX, but i will be holding the result of INT_MAX + 1 (side effect of post increment), which is essentially signed integer overflow. The loop condition (INT_MAX < INT_MAX) result in false and loop exits. The value of variable i not used anywhere in the program after the loop body but, of course, once the loop exits it is holding the result of INT_MAX + 1.

Does this program possess undefined behavior?

PS:

does-integer-overflow-cause-undefined-behavior-because-of-memory-corruption

is-it-undefined-behavior-if-the-intermediate-result-of-an-expression-overflows

In both the above question, the value of variable/expression resulting in overflow is used in some way or other.


Solution

  • Does this program possess undefined behavior?

    Yes, that is very clear.

    You don't have to access the value of i after it overflows for the overflow to have happened, and once the overflow has happened, you have invoked undefined behavior.

    If somebody compiles your program with GCC and uses the -ftrapv flag, your program will crash as soon as the overflow occurs, regardless of whether you would later have attempted to access i.