Can java code cause segmentation fault in linux?

Mr Pang :

It is said that java is more safer in memory handling than C. In C it is very easy to cause a segmentation fault by accessing invalid pointer. Now I would like to know whether java code can also cause segmentation fault. Can someone give me an example?

Level_Up :

Typically in normal Java program you do not have this problem. But yes if you use thing like sun.misc.Unsafe you can cause segmentation fault. But that why Unsafe is called Unsafe. Normally you don't have to use it so you do not have this problems in your code.

For more information: Where is sun.misc.Unsafe documented?

Bug reported based with Segmentation error with sun.misc.Unsafe https://github.com/eclipse/openj9/issues/4153

Here one example how you can test:

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);
}

}

When I execute on Ubuntu 18.04 I get this output: A fatal error has been detected by the Java Runtime Environment:

SIGSEGV (0xb) at pc=0x00007f05bdf04d27, pid=4145, tid=4147

JRE version: OpenJDK Runtime Environment (10.0.2+13) (build 10.0.2+13-Ubuntu-1ubuntu0.18.04.4)

On Windows I think it will be similar output with fatal error description.

Good luck to all!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=89132&siteId=1