Jerikc XIONG
Jerikc XIONG

Reputation: 3607

Will the GC dispose/deallocate the memory allocated in jni automatically on Android?

I allocate the memory and new the ByteBuffer object in JNI as following:

uint8_t* pBuffer = (uint8_t*)malloc(size);
// fill the pBuffer
jobject byteBufferInJni = (*env)->NewDirectByteBuffer(env, pBuffer, size);

Then pass the byteBufferFromJni to Java layer like this:

callback(byteBufferInJni);

In java layer, get the Object byteBufferInJni.

The question is:

If i dereference the byteBufferInJni in java, like this:

byteBufferInJni = null;

Will the pBuffer disposed/deallocated by GC ?

Upvotes: 1

Views: 519

Answers (1)

SomeRandomDude
SomeRandomDude

Reputation: 36

Nope, the JVM does not know that malloc was used and the memory should be deallocated with free. If the ByteBuffer was to call free automatically, the JVM would crash if the memory is statically allocated:

#include <stdlib.h>

int main()
{
    char *str = "Hello, World!";
    free(str); // Never do this!
}

It is your responsibility to free it. There are many methods to acquire memory and require very specific ways to deallocate it, e.g. malloc/free, new/delete, new[]/delete[].

Upvotes: 1

Related Questions