如何在JNI中释放返回的对象?

时间:2019-04-09 05:50:02

标签: java android c++ android-ndk java-native-interface

我的程序中发生了内存泄漏。

请帮助我找到内存泄漏的位置,并告诉我如何解决它,谢谢。

代码

extern "C" JNIEXPORT jbyteArray JNICALL
Java_cn_test_encoder_JNIEncoder_encodeEncryptBuff(
        JNIEnv* env,
        jobject obj,
        jbyteArray ucInBuffer,
        jintArray unInbufferLen,
        jintArray unOutbufferLen) {

    jbyte *bytes = env->GetByteArrayElements(ucInBuffer, 0);;

    int chars_len = env->GetArrayLength(ucInBuffer);

    unsigned char* chars = (unsigned char *) malloc(chars_len);
    memset(chars,0,chars_len);
    memcpy(chars, bytes, chars_len);
    env->ReleaseByteArrayElements(ucInBuffer, bytes, 0);

    int inLength = env->GetArrayLength(unInbufferLen);
    int* inArray = env->GetIntArrayElements(unInbufferLen,0);

    int outLength = env->GetArrayLength(unOutbufferLen);
    int* outArray = env->GetIntArrayElements(unOutbufferLen,0);

    unsigned char* encryptBuff = Encode_Encrypt_Buff(chars, (unsigned int*)inArray, (unsigned int*)outArray);

    jbyteArray bArray=env->NewByteArray(*outArray);

    env->SetByteArrayRegion(bArray, 0, *outArray, (jbyte *)encryptBuff);

    env->ReleaseIntArrayElements(unInbufferLen, inArray, NULL);
    env->ReleaseIntArrayElements(unOutbufferLen, outArray, NULL);
    free(chars);

    return bArray;  // java needs byte array
}

内存使用情况

  

memory usage

1 个答案:

答案 0 :(得分:0)

我用delete encryptBuff解决了这个问题,不需要释放返回的对象。

代码

...

free(chars);

delete encryptBuff;  // Add this line

return bArray;

新内存使用情况

  

new memory usage