2

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?

tilmik
  • 143
  • 1
  • 2
  • 11
  • You don't check the return from `NewByteArray`. So either there is a problem with not checking the result, or else there is the possibility of an exception, which would not be safe in this code. Anyway, just use `std::vector` instead of explicit `new` and `delete`. Also, keep in mind when you write exploration code like this, that it's a good idea to be able to verify results. So instead of random numbers, fill the array with recognizable values. – Cheers and hth. - Alf Jun 04 '15 at 04:15
  • Thanks for the suggestions. Can you please describe a little what you meant by _"there is the possibility of exception"_? What checking I should do with **NewByteArray**? – tilmik Jun 04 '15 at 04:43
  • You just need to read the documentation. I don't know how `NewByteArray`signals failure. I did know that 15 years ago, but not today. But there is a possibility of failure, hence there is some failure indication mechanism. – Cheers and hth. - Alf Jun 04 '15 at 04:56

1 Answers1

6

The Java GC should clean up any objects you allocate.

See this answer for more details.

Community
  • 1
  • 1
Buddy
  • 10,874
  • 5
  • 41
  • 58