据说java在内存处理上比C更安全。 在 C 中,访问无效指针很容易导致段错误。现在我想知道java代码是否也会导致段错误。 有人可以给我举个例子吗?
最佳答案
通常在普通的 Java 程序中你不会遇到这个问题。
但是是的,如果你使用像 sun.misc.Unsafe
这样的东西,你可能会导致段错误。但这就是 Unsafe
被称为 Unsafe
的原因。通常您不必使用它,因此您的代码中不会出现此问题。
更多信息: Where is sun.misc.Unsafe documented?
错误报告基于 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);
}
}
当我在 Ubuntu 18.04 上执行时,我得到了这个输出:
Java 运行时环境检测到 fatal error :
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 上,我认为它会是带有 fatal error 描述的类似输出。
祝大家好运!
关于java - java代码会导致linux中的段错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55397570/