4 ms·
Nowadays, UB is used pretty much as a license to make optimizer go brrrr. But back in the day, I think it was used to allow implementations wiggle room on wheth
by bitwize 2y ago
Nowadays, UB is used pretty much as a license to make optimizer go brrrr. But back in the day, I think it was used to allow implementations wiggle room on whether a particular construct was erroneous or not -- in contrast to other specifications like "it is an error" (always erroneous) or "implementation-defined behavior" (always legitimate; compiler must emit something sensible, exactly what is not specified). In the null pointer case, it makes sense for kernel-mode code to potentially indirect to address 0 (or 0xffffffff, or whatever your architecture designates as null), while user-space code can be reasonably considered never to legitimately access that address because the virtual memory never maps it as a valid address. So accessing null is an error in one case and perfectly cromulent in the other. So the standard shrugs its shoulders and says "it's undefined".
- lmm 2y agoThe original motivation was to permit implementations to do the reasonable, friendly thing, and trap whenever the program dereferences a null pointer. Since C compilers want to reorder or elide memory accesses, you can't really define explicit semantics for that (e.g. you want it to be ok to move the memory access before or after a sequence point) - the JVM has to do a lot of work to ensure that it throws NullPointerException at the correct point when it happens, and this slows down all programs even though no-one sane has their program intentionally trigger one. But the intention was to permit Java-like behaviour where your code would crash with a specific error immediately-ish, maybe not on the exact line where you dereferenced null but close to it. Ironically compiler writers then took that standard and used it to do the exact opposite, making null dereference far more dangerous than even just unconditionally reading memory address 0.
- uecker 2y agoCompiler writers did both: https://godbolt.org/z/z9WKs5aYv https://godbolt.org/z/z9WKs5aYv