Why this little program output True? Is GCC's overflow protection?

2
#include<stdio.h>

void main(){

    int x = 0x80000000;
    if((x-1)<1)
        printf("True");
    else
        printf("False");

}

this is from csapp practice 2.44, if this is compiler's operation, how to close it?

c
gcc
overflow
asked on Stack Overflow Dec 17, 2020 by frozen

1 Answer

2

Assuming an int is 32 bit, the constant 0x80000000 is outside the range of an int and has type unsigned int. When used to initialize an int it is converted in an implementation defined manner. For gcc, that conversion results in x having the value -231 (whose representation happens to be 0x80000000) which is the smallest value it can hold.

Then when you attempt to calcuate x-1, it causes signed integer overflow which is undefined behavior. As an example of this, if I compile this code under gcc 4.8.5 with -O0 or -O1 I get "False" as output, and if I compile with -O2 or -O3 it outputs "True".

answered on Stack Overflow Dec 17, 2020 by dbush

User contributions licensed under CC BY-SA 3.0