据说Java在内存处理方面比C更加安全。在C中,通过访问无效指针很容易导致分段错误。现在我想知道Java代码是否也会导致分段错误。有人能举个例子吗?
sun.misc.Unsafe
这样的东西,就可能会导致分段错误。但这就是为什么Unsafe
被称为Unsafe
。通常你不必使用它,所以你的代码不会出现这些问题。sun.misc.Unsafe
的分段错误报告的错误:
https://github.com/eclipse/openj9/issues/4153
下面是一个测试示例:import java.lang.reflect.Field;
import sun.misc.Unsafe;
public class MainClass {
public static void main(String[] args)
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
Unsafe unsafe = (Unsafe) theUnsafe.get(null);
long ten = 10;
byte size = 1;
long mem = unsafe.allocateMemory(size);
//Put here the wrong address!!!
unsafe.putAddress(1, ten);
//With this will work:
//unsafe.putAddress(mem, ten);
long readValue = unsafe.getAddress(mem);
System.out.println("result: " + readValue);
}
}
Java运行时环境检测到致命错误:
SIGSEGV(0xb)于pc=0x00007f05bdf04d27,pid=4145,tid=4147
JRE版本:OpenJDK Runtime Environment(10.0.2+13)(build 10.0.2+13-Ubuntu-1ubuntu0.18.04.4)
在Windows上,我认为将会有类似的致命错误描述。
祝大家好运!
Java有一个用于执行本地代码(JNI)的接口。通过这个接口,可以调用用C编写的代码,从而可能导致分段错误。
JVM代码本身中的错误可能会导致分段错误,但这种情况相当罕见。
对于纯Java,不会出现这种情况。该语言被设计为仅允许引用指向有效地址或null。如果引用指向null,则会出现NullPointerException。