Hacker News new | ask | show | jobs
by uecker 1 day ago
The check is removed only if you already dereference the pointer before doing the check. But then, you also get the trap before the check. So the compiler eliding the check is not making this worse - as long as the zero page is not mapped.

In any case, you can also configure GCC to not do this, and you can also configure it to insert explicit null checks before dereferencing a pointer. So C can offer you security and reproducibility (in this aspect).

1 comments

No, it's also removed if you dereference it later on, that's why it is said, that UB has time traveling behaviour. This means, that the compiler can emit a program, that let's you access data without a security check, while the crash only comes later. Also the crash can be removed, because dereferencing it is UB anyway, so the compiler does not need to emit it.
The check can not be removed if it becomes before the access because in this case the program has no UB.

If there were UB, a compiler in C is not allowed to move (time-travel) UB before any observable behavior. This was never allowed by in C (int contrast to C++), but the wording was not clear, which we fixed in C23.

If there is no check, you are right that the access itself is UB and there is no requirement to trap in ISO C, but this is something compilers explicitly support. (and it might be required by POSIX, but I am not sure)