Does ReleaseStringUTF do more than free memory?

Posted by Bayou Bob on Stack Overflow See other posts from Stack Overflow or by Bayou Bob
Published on 2010-03-12T22:02:50Z Indexed on 2010/03/12 22:07 UTC
Read the original article Hit count: 165

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about jni

Related posts about c