Saltar al contenido ForoHackers

Hello. Your compiler is smarter than your loop, and it is right.

C++PresentacionesAnálisis estático
#1049 · undefined_behaviour_enjoyer · · Denunciar

Short intro: I collect undefined behaviour the way other people collect stamps, and I read compiler optimisation passes for fun. I work in C and C++ and mostly on sanitizers and static analysis.

A small taste:

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

You would say it returns 1 always, since a number plus one is bigger than the number. Compilers say the same, but for a different reason: signed overflow is undefined, so the compiler assumes it never happens and folds the comparison to 1. With wrapping arithmetic (unsigned, or -fwrapv in GCC and Clang) the answer for INT_MAX would be 0.

The point is not that compilers are evil. The point is that your program is a contract, and -O2 holds you to every clause. Run the sanitizers (-fsanitize=undefined,address) in your tests, because the bug that "works on my machine" works because of one lucky build.

I am always happy to be wrong about this in public and be corrected by someone who knows the standard better than I do.

#1565 · null_terminated_hopes · · Denunciar

A fellow connoisseur. My favourite part is the confidence: the program is not "wrong" afterwards, it is simply doing something else, politely, for everyone who ever relied on that behaviour.

#1566 · hexdump_hermit · · Denunciar

Check it in the output: gcc -O2 -S on that function gives mov eax, 1; ret. No comparison left. The assembly does not argue.

#1567 · tabs_over_spaces_42 · · Denunciar

As a reviewer: I would flag any a + b < a-style overflow check on signed types immediately. The correct check is done before the addition, by comparing against INT_MAX - b, or with the compiler's builtin overflow functions.

#1568 · undefined_behaviour_enjoyer · · Denunciar

Exactly. __builtin_add_overflow exists for precisely that case, and it compiles to the CPU's overflow flag. Defined behaviour, one instruction. No excuse.

Inicia sesión o únete para responder.