2 ms·
It is UB for any C compiler and for any architecture because the language defines it as such. However, because it is UB, the compiler doesn't need to do anythi
by int_19h 2y ago
It is UB for any C compiler and for any architecture because the language defines it as such.
However, because it is UB, the compiler doesn't need to do anything special if there's no trap on null dereference, since "reading something" is a perfectly valid subset of UB. The only thing that it needs to ensure is that no global, local, or heap-allocated C object can end up at address 0, which is easily done by "wasting" a single word at that address (or using it for some internal purposes).
It may still be that there is something useful at address 0 that some code may want to access. For example, in real-mode x86, the interrupt vector table starts at that address, so if you want to change what gets called to handle INT 0h, you'd need to write into it. But at this point you're already deep into architecture-specific stuff, and so it's not unreasonable to expect you to use some special facilities that a compiler for this architecture might provide to enable it, instead of the usual pointer dereference.
- shultays 2y agoI am a bit confused, in another post you mentioned The C spec only requires that integer constant expressions that have zero value are nullptrs. The moment you assign it to an int variable, it's no longer a constant expression as far as the language is concerned, so if you then cast that int variable to a pointer, the result is indeterminate It is not an integer constant that gets assigned to a pointer so this is not a null pointer in that case? It is just a pointer with address of 0 (which very well might be the implementation of nullptr but from my understanding that is not required?) so shouldn't nullptr dereferencing rule not apply here?
- int_19h 2y agoIndeed, it's UB not because it's dereferencing a nullptr; it's UB because it's dereferencing an invalid pointer (i.e. a pointer that does not point to any C object). An implementation could declare that there is a valid object at address 0, I suppose, but strictly conforming code cannot rely on this. As far as I remember, the only ints you can cast to a pointer and then safely use are those that were cast from (valid) pointers in the first place.