Why doesn't the compiler warn you of a possible Undefined Behavior?

I read the famous Undefined Behavior can trigger a message while traveling and noticed this part:

First of all, you may notice a "one by one" error in the control loop. As a result, the function reads one by one before giving up. The classic compiler is not particularly care. It simply generates code to read an element outside the bounds (despite the fact that this is a violation of language rules), and it will return true if the memory passed after the end of the array turned out to be the same.

A postclassical compiler, on the other hand, can perform the following analysis:

The first four times through the loop, the function can return true.

When I equal 4, the code executes undefined behavior. Since undefined behavior allows me to do whatever I want, I can completely ignore it in this case and continue on the assumption that I never 4. (If the assumption is violated, something unpredictable happens, but this is normal, because the undefined behavior gives me permission to be unpredictable. )

According to this notation, the (newer) compiler can already act on undefined Behavior during compilation, which means that it is quite capable of determining the behavior of undefined Behavior in some cases. Instead of letting the demons fly out of your nose or spawning dragons by excluding the UB code or just transforming it, because it allowed why the compiler did not issue a warning that this was probably not intended?

+4
source share
3 answers

. , , . , .

, , undefined, undefined. .

undefined, , -W -Wall -Wextra -O2 gcc. ( , -O2, )

+5

. - , . .

, :

(, jenkins gcc clang).

(, )

:

cppcheck main.cpp

:

[main.cpp: 8]: () Array [4] ' 4, .

, . , valgrind .

, , , . , .. . efence, duma .

, , .

(, gtest) . . , / - .

- .

, : !

+2

, , , Undefined, , , , , , , , , , .

, , , - , (*), . , , , , , , , " , xxx ", " , xxx , xxx, " " , yyy, xxx ". [ xxx, ].

(*) . , x+1>y 0, x == INT_MAX , , , , ; 1, 0 , , , ).

xxx , , , , , , , . , , :

if (xxx) log_message("xxx was okay at checkpoint #57");

[ xxx , UB, , , x , ]. , (, " , xxx " ) , , , , .

+1

All Articles