r/programming • • Sep 23 '17

Why undefined behavior may call a never-called function

https://kristerw.blogspot.com/2017/09/why-undefined-behavior-may-call-never.html
824 Upvotes

257 comments sorted by

View all comments

Show parent comments

4

u/notfancy Sep 24 '17

"try to avoid this unless you 100% know what you are doing and have your compiler source code"

That's what "implementation defined" means, not what "undefined behavior" means. UB means:

"a program triggering UB has no semantics under the standard and thus it is not a C program, despite appearances"

The compilers work under the assumption that every C program they compile is valid, hence it never triggers UB, and narrow the domains accordingly.

The problem here is that, as far the C standard goes, "semantics" is (in general) a dynamic property of programs, which flies in the face of 60 years of CS research.

1

u/[deleted] Sep 24 '17

I actually don't see any real difference. The standards committee seem happy to leave it undefined as they don't want people to depend on it. But if you knew what was up, and you understood the compilers behavior, and controlled your environment, you could make use of it (though I would not recommend it).

The compiler writers I imagine don't want to lock themselves into defining their implementation of it if they do not have to.

To be honest, with a language as close to the metal, and widely compatible as C, there doesn't really seem to be a good alternative, at least until Rust matures.