Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using memory allocated by sun.misc.Unsafe.allocateMemory() in native code

I am trying to allocate memory using sun.misc.Unsafe.allocateMemory() and access it in native code.

however, it seems the long value returned by allocateMemory doesn't quite work as the right address in C code.

            Unsafe unsafe = getUnsafe();
            long address = unsafe.allocateMemory(64);

            for (int i = 0; i < 64; i += 8)
                unsafe.putByte(memory + i, (byte) 0xFF);

            nativeMethod(address);

However in my native code when I try to access 'address' as a pointer, it doesn't work :(

Update: I have attached an image showing the issue. I passed the 'address' to the native code, however, examining the memory at that location doesnt show the 0xFF values I put in there.

Image: http://i.stack.imgur.com/KoIYG.png

enter image description here

like image 864
pdeva Avatar asked Dec 21 '22 02:12

pdeva


1 Answers

I think it's working perfectly fine! Your "for" loop sets every eighth byte to 0xff, and if you look closely at the display and count, you'll see that every eighth byte is 0xff. There are some other random values in there because Unsafe. allocateMemory() doesn't return zeroed memory; it returns uninitialized memory, just like C's malloc().

If you changed that "i += 8" to just "i++", then every byte would be 0xff; it'd be worth doing that experiment to prove to yourself that it's working.

like image 56
Ernest Friedman-Hill Avatar answered Dec 28 '22 23:12

Ernest Friedman-Hill