Is it possible to produce undefined behavior when dereferencing `null` in Java?

前端 未结 4 1890
一生所求
一生所求 2021-02-20 03:28

I just learned that dereferencing null in C and C++ can sometimes produce undefined results. This is very intriguing to me, like all bizarre programming behaviors

4条回答
  •  伪装坚强ぢ
    2021-02-20 04:09

    You cannot get undefined behaviour from a nullin pure Java (unless there is a serious bug in the JVM!). The JLS specifies that any attempt to explicitly or implicitly dereference a null will result in a NullPointerException. There is no wriggle room that allows for any undefined behaviour that is related to the handling of null.

    However, if your application includes ... or makes use of ... native methods, it is possible for one of those methods to mishandle a null in a way that results in undefined behaviour. You can also get undefined behaviour using the Unsafe class. But both of these scenarios mean you are not using pure Java. (When you step outside of pure Java, the guarantees of the JLS no longer necessarily apply!)

    (The one area where unpredictable things can happen is in multi-threading. But even then, the set of possible behaviours is defined. For instance, if you don't synchronize state sharing adequately you may see stale values in fields. But you won't see totally random values ... or bad addresses that result in segmentation violations.)


    If it is possible, then it would be possible for a malicious program to do so as well, which would open up an interesting security concern.

    A malicious program can do almost anything. But the correct way to deal with this is to execute code that you don't trust (i.e. possibly malicious code) in a sandbox. A typical sandbox would forbid calling Unsafe or loading a native library ... and lots of other things that a malicious program could exploit.

提交回复
热议问题