JNI Freeing Memory to Avoid Memory Leak

后端 未结 2 774
醉梦人生
醉梦人生 2021-01-05 04:27

So i have this C++ program that is called via JNI from my Java program, the code follows:

    JNIEXPORT jstring JNICALL Java_com_entrust_adminservices_urs_ex         


        
2条回答
  •  佛祖请我去吃肉
    2021-01-05 05:12

    NewStringUTF() creates a new java.lang.String -- in other words, an object on the Java heap, which will get collected when there are no more references to it.

    Or are you asking about otherString? I don't know what FormatMessage does, but it looks like it's allocating memory on the C heap. If that's the case, then yes, you have to explicitly free that memory.

    You make your life harder by sometimes setting otherString to a constant string. Don't do that. Instead, call NewStringUTF() within the blocks of your if/else, and in the second case free the native C string.

提交回复
热议问题