Saltar al contenido ForoHackers

x + 1 > x: a function the compiler turns into `return 1`

CCompiladoresDepuración
#1175 · null_terminated_hopes · · Denunciar

Some gloomy C for the weekend.

int always_greater(int x) {
    return x + 1 > x;
}

You would say: for INT_MAX, x + 1 wraps around and the answer is 0. In C, signed integer overflow is undefined behaviour, so the compiler is allowed to assume it never happens. If it never happens, x + 1 > x is true for every x it has to care about, and at -O2 GCC and Clang compile the function to "return 1". Look at the assembly:

always_greater:
    mov eax, 1
    ret

The check you thought you had written is gone. The same reasoning rewrites overflow checks written as if (a + b < a) for signed a and b: the compiler may reduce it to b < 0, which no longer detects the overflow at all.

For unsigned types the standard defines wraparound, so x + 1 > x is false for the maximum value and the compiler must keep it.

What to do:

  • Check before the operation. For a + b with b >= 0: if (a > INT_MAX - b). For negative b the limit is the other end: if (a < INT_MIN - b).
  • Use the compiler's checked arithmetic builtins (__builtin_add_overflow) when available.
  • Compile test builds with -fsanitize=undefined, which reports the overflow at run time.
  • -fwrapv makes signed wrap defined, at the cost of some optimisations, and it is a flag, not a standard.

It is not the compiler being malicious. It is the compiler taking the contract literally. The contract is the part we forgot to read.

#2009 · undefined_behaviour_enjoyer · · Denunciar

Excellent, and the standard-lawyer footnote: the compiler is not required to produce "return 1" either. Anything is allowed, which is exactly why "it worked in testing" proves nothing. The one thing it is not allowed to do is tell you in advance.

#2010 · ElDelPuntoYComa · · Denunciar

Precisión: -fsanitize=undefined detecta esto en ejecución, pero solo en los caminos que tus pruebas recorren, así que no sustituye a la comprobación previa. Y __builtin_add_overflow es una extensión de GCC y Clang; si necesitas portabilidad, la comprobación manual con INT_MAX e INT_MIN sigue siendo la opción estándar.

#2011 · null_terminated_hopes · · Denunciar

Fair point: tests only cover the paths you thought of, and the builtin is not portable. Good example of why the contract needs reading in full. I will tell myself I meant it as a teaching exercise.

Inicia sesión o únete para responder.