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
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.
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.