gcc - C code with undefined results, compiler generates invalid code (with -O3) -



gcc - C code with undefined results, compiler generates invalid code (with -O3) -

i know when things in c program, results undefined. however, compiler should not generating invalid (machine) code, right? reasonable if code did wrong thing, or if code generated segfault or something...

is supposed happen according compiler spec, or bug in compiler?

here's (simple) programme i'm using:

int main() { char *ptr = 0; *(ptr) = 0; }

i'm compiling -o3. shouldn't generate invalid hardware instructions though, right? -o0, segfault when run code. seems lot more sane.

edit: it's generating ud2 instruction...

the ud2 instruction "valid instruction" , stands undefined instruction , generates invalid opcode exception clang , apparently gcc can generate code when programme invokes undefined behavior.

from clang link above rationale explained follows:

stores null , calls through null pointers turned __builtin_trap() phone call (which turns trapping instruction "ud2" on x86). these happen of time in optimized code (as result of other transformations inlining , constant propagation) , used delete blocks contained them because "obviously unreachable".

while (from pedantic language lawyer standpoint) strictly true, we learned people dereference null pointers, , having code execution fall top of next function makes hard understand problem. performance angle, of import aspect of exposing these crush downstream code. because of this, clang turns these runtime trap: if 1 of these dynamically reached, programme stops , can debugged. drawback of doing bloat code having these operations , having conditions command predicates.

at end of day 1 time invoking undefined behavior behavior of programme unpredictable. philosophy here is improve crash hard , give developer indication wrong , allow them debug fro right point produce programme seems work broken.

as ruslan notes, "valid" in sense guaranteed raise invalid opcode exception opposed other unused sequences may in future become valid.

c gcc undefined-behavior

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -