What your experiment shows is that it happens to work on your particular computer. That doesn't mean it's "ok".
In particular, this line:
int &surprise_reference=*(int*)0;
is invalid C++ code, because (exactly as you said) a reference is not allowed to point to a NULL pointer. The result of doing something that's not allowed by the C++ standard is undefined behavior. In this particular case, on your particular computer, the undefined behavior happens to be pretty benign, but that doesn't make it predictable, or always OK.
See https://isocpp.org/wiki/faq/references#refs-vs-ptrs for more details. One thing that they point out in particular is that, because the compiler knows that creating a null reference is illegal, it may assume that you haven't done it -- for instance, if you have a function that takes p
as a parameter, and you write
int &q = *(int*)p;
if (p == NULL)
...
it may conclude from the reference creation that p
is known to be non-NULL, and optimize away the check. Then, if you pass in a NULL pointer for p
, things may go badly wrong.
(That sort of assumption-and-optimization, by the way, is how a lot of the bad things from undefined code happen.)