JNI Freeing Memory to Avoid Memory Leak

后端 未结 2 759
醉梦人生
醉梦人生 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 04:54

    You don't have to worry about the memory allocated by NewStringUTF as that will be taken care of by the Java garbage collector.

    But you have to free the lpMsgBuf as you are passing FORMAT_MESSAGE_ALLOCATE_BUFFER to FormatMessage (i.e. you have to use LocalFree to free that buffer), see the FormatMessage documentation.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题