Note that there are some explanatory texts on larger screens.

plurals
  1. PODoes ReleaseStringUTF do more than free memory?
    primarykey
    data
    text
    <p>Consider the following C code segments.</p> <p>Segment 1:</p> <pre><code>char * getSomeString(JNIEnv *env, jstring jstr) { char * retString; retString = (*env)-&gt;GetStringUTFChars(env, jstr, NULL); return retString; } void useSomeString(JNIEnv *env, jobject jobj, char *mName) { jclass cl = (*env)-&gt;GetObjectClass(env, jobj); jmethodId mId = (*env)-&gt;GetMethodID(env, cl, mName, "()Ljava/lang/String;"); jstring jstr = (*env)-&gt;CallObjectMethod(env, obj, id, NULL); char * myString = getSomeString(env, jstr); /* ... use myString without modifing it */ free(myString); } </code></pre> <p>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.</p> <p>I know that changing getSomeString as follows would be safer (and probably preferable).</p> <p>Segment 2:</p> <pre><code>char * getSomeString(JNIEnv *env, jstring jstr) { char * retString; char * intermedString; intermedString = (*env)-&gt;GetStringUTFChars(env, jstr, NULL); retString = strdup(intermedString); (*env)-&gt;ReleaseStringUTFChars(env, jstr, intermedString); return retString; } </code></pre> <p>Because of our 'process' I need to build an argument on why getSomeString in Segment 2 is preferable to Segment 1.</p> <p>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.</p> <p>Thanks in advance.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload