简体   繁体   中英

How to free memory allocated by native method on Java side?

I am trying to pass a byte array (with random data) from native to Java and I am not sure if this causes any memory leak or not. Here's the C++ code.

JNIEXPORT jbyteArray JNICALL Java_com_sample_test_jni_TestJNI_return_1byte_1array
(JNIEnv *env, jobject obj) {
  unsigned char *byteArray = new unsigned char[LENGTH];
  srand(12345);
  for(int i = 0;i < LENGTH;i++) {
    byteArray[i] = rand() % 64;
  }
  jbyteArray data = (env)->NewByteArray(LENGTH);
  env->SetByteArrayRegion(data, 0, LENGTH, (jbyte*)byteArray);
  delete(byteArray);
  return data;
}

And here's the Java code.

class TestJNI {
  static {
    System.loadLibrary("foobar");
  }
  public native byte[] return_byte_array();
  public static void main(String[] args) {
    byte[] data = new TestJNI().return_byte_array();
    System.out.println("Data length " + data.length);
  }
}

My doubt is whether the jbytearray allocated in native code will be garbage-collected by Java. I cannot free it in native side.

Also, are there good docs which describe JNI memory management with examples?

The Java GC should clean up any objects you allocate.

See this answer for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM