Java 字节数组的 JNI 内存泄漏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18668135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:59:51  来源:igfitidea点击:

JNI memory leak from byte array

javac++memory-leaksjava-native-interface

提问by Tyler Davis

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

我有一个 java 程序,它多次调用本机函数。我的问题是这个函数有内存泄漏,我为摆脱它所做的一切都会导致内存转储。任何帮助将不胜感激。

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 above ^ code 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!

任何帮助,将不胜感激。谢谢!

回答by JustinDanielson

ReleaseByteArrayElements will also free the memory if you use the JNI_ABORT param. So when you're doing the delete and release later on, one of those pointers is pointing to uninitialized memory which is causing the dump.

如果您使用 JNI_ABORT 参数,则 ReleaseByteArrayElements 也将释放内存。因此,当您稍后进行删除和释放时,这些指针之一指向导致转储的未初始化内存。

One of these will work, I fairly certain it is the first one that works.

其中一个会起作用,我相当肯定它是第一个起作用的。

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

Try this if the first fails.

如果第一个失败,请尝试此操作。

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

Put a print statement after the ReleaseByteArrayElements, you will see that your program is executing beyond that command and crashing on the Release/Delete[]

在 ReleaseByteArrayElements 之后放置一条打印语句,您将看到您的程序正在执行超出该命令并在 Release/Delete[] 上崩溃

Search for "Table 4-10 Primitive Array Release Modes"

搜索“表 4-10 原始数组释放模式”