When I try to get memory adress of each element in array.I tried to run code as below
import sun.misc.Unsafe;
import java.lang.reflect.Field;
import static sun.misc.Unsafe.getUnsafe;
public class test_arr {
public static void main(String args[]) throws NoSuchFieldException, IllegalAccessException {
Field theUnsafeField = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafeField.setAccessible(true);
Unsafe u = (Unsafe) theUnsafeField.get(null);
int[][] arr = new int[3][4];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.println(u.getAddress(arr[i][j]));
}
}
}
}
But i meet this error. A fatal error has been detected by the Java Runtime Environment
I have looked the https://mishadoff.com/blog/java-magic-part-4-sun-dot-misc-dot-unsafe/ But i can't fix this error. if someone konws how to fix it,please tell me,thanks!
As suggested by the comments I changed the code.
public class test_arr {
private static long normalize(int value) {
if (value >= 0) return value;
return (~0L >>> 32) & value;
}
static long toAddress(Object obj) throws NoSuchFieldException, IllegalAccessException {
Object[] array = new Object[]{obj};
Field theUnsafeField = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafeField.setAccessible(true);
Unsafe u = (Unsafe) theUnsafeField.get(null);
long baseOffset = u.arrayBaseOffset(Object[].class);
return normalize(u.getInt(array, baseOffset));
}
public static void main(String args[]) throws NoSuchFieldException, IllegalAccessException {
int[][] arr = new int[3][4];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
double random = Math.random();
arr[i][j] = (int) (random);
}
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
long address = toAddress(arr[i]);
System.out.println((Long.toHexString(address)));
}
}
}
}
The output looks like you can infer the addresses of the array elements.But it's still not possible to know the exact position of each element.
d57431a7
d57431a7
d57431a7
d57431a7
d57431ab
d57431ab
d57431ab
d57431ab
d57431af
d57431af
d57431af
d57431af
I still want to know the exact memory address of each array element, how should I do that, thanks!