JNI memory leak from byte array

I have a java program that calls a native function many times. My problem is that this function has a memory leak, and everything I do to get rid of it causes a memory dump. Any help would be greatly appreciated.

This is my code.

JNIEXPORT void JNICALL Java_class_method_getInput (JNIEnv *env, jobject obj) { if (inputIsAvailable) { int size = getBufferCurrentIndex(); size -= getBufferReadIndex(); size *= 2; char *finalSendArray = new char[size]; getCommand(finalSendArray); jbyteArray byteArray = env->NewByteArray(size / 2); env->SetByteArrayRegion(byteArray, 0, size / 2, (jbyte*) finalSendArray); while(methodID == 0) { jclass cls = env->GetObjectClass(obj); methodID = env->GetMethodID(cls, "setCommand", "([B)V" ); } env->CallVoidMethod(obj, methodID, byteArray); //env->ReleaseByteArrayElements(byteArray, (jbyte*) finalSendArray, JNI_ABORT); 

My problem is that the code above causes a memory dump, if it is uncommented, if it is not uncommented, my program runs out of memory in minutes

  env->DeleteLocalRef(byteArray); delete[] finalSendArray; } } 

Any help would be appreciated. Thanks!

+4
source share
1 answer

ReleaseByteArrayElements will also free memory if you use the JNI_ABORT parameter. Therefore, when you do the deletion and release later, one of these pointers points to uninitialized memory that causes a dump.

One of them will work, I'm sure it works first.

 env->ReleaseByteArrayElements(byteArray, (jbyte*) finalSendArray, JNI_ABORT); delete[] finalSendArray; 

Try this if the first crash.

 env->ReleaseByteArrayElements(byteArray, (jbyte*) finalSendArray, JNI_ABORT); env->DeleteLocalRef(byteArray); 

Place the print statement after ReleaseByteArrayElements, you will see that your program executes this command and crashes on Release / Delete []

Search "Table 4-10 Production modes of primitive arrays"

+2
source

Source: https://habr.com/ru/post/1501027/


All Articles