Does ReleaseStringUTF do more than free memory?
- by Bayou Bob
Consider the following C code segments.
Segment 1:
char * getSomeString(JNIEnv *env, jstring jstr) {
char * retString;
retString = (*env)->GetStringUTFChars(env, jstr, NULL);
return retString;
}
void useSomeString(JNIEnv *env, jobject jobj, char *mName) {
jclass cl = (*env)->GetObjectClass(env, jobj);
jmethodId mId = (*env)->GetMethodID(env, cl, mName, "()Ljava/lang/String;");
jstring jstr = (*env)->CallObjectMethod(env, obj, id, NULL);
char * myString = getSomeString(env, jstr);
/* ... use myString without modifing it */
free(myString);
}
Because myString is freed in useSomeString, I do not think I am creating a memory leak; however, I am not sure. The JNI spec specifically requires the use of ReleaseStringUTFChars. Since I am getting a C style 'char *' pointer from GetStringUTFChars, I believe the memory reference exists on the C stack and not in the JAVA heap so it is not in danger of being Garbage Collected; however, I am not sure.
I know that changing getSomeString as follows would be safer (and probably preferable).
Segment 2:
char * getSomeString(JNIEnv *env, jstring jstr) {
char * retString;
char * intermedString;
intermedString = (*env)->GetStringUTFChars(env, jstr, NULL);
retString = strdup(intermedString);
(*env)->ReleaseStringUTFChars(env, jstr, intermedString);
return retString;
}
Because of our 'process' I need to build an argument on why getSomeString in Segment 2 is preferable to Segment 1.
Is anyone aware of any documentation or references which detail the behavior of GetStringUTFChars and ReleaseStringUTFChars in relation to where memory is allocated or what (if any) additional bookkeeping is done (i.e. local Reference Pointer to the Java Heap being created, etc). What are the specific consequences of ignoring that bookkeeping.
Thanks in advance.