You cannot directly access any memory location! It must be managed by the JVM. A security exception occurs or EXCEPTION_ACCESS_VIOLATION. This can cause the JVM to crash. But if we allocate memory from code, we can access bytes.
public static void main(String[] args) {
Unsafe unsafe = null;
try {
Field field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = (sun.misc.Unsafe) field.get(null);
} catch (Exception e) {
throw new AssertionError(e);
}
byte size = 1;
long allocateMemory = unsafe.allocateMemory(size);
unsafe.putByte(allocateMemory, "a".getBytes()[0]);
byte readValue = unsafe.getByte(allocateMemory);
System.out.println("value : " + new String(new byte[]{ readValue}));
}
source
share