78

The book "Essential JNI: Java Native Interface" by Rob Gordon contains the following code example to convert a jstring to a C string:

const char* utf_string;
jboolean isCopy;
utf_string = env->GetStringUTFChars(str, &isCopy);
/* ... use string ... */
if (isCopy == JNI_TRUE) {
    env->ReleaseStringUTFChars(str, utf_string);
}

Note that it only calls ReleaseStringUTFChars if isCopy is true.

But the book Java Native Interface: Programmer's Guide and Specification (alternate link: http://192.9.162.55/docs/books/jni/html/objtypes.html#5161) says:

The ReleaseString-Chars call is necessary whether GetStringChars has set *isCopy to JNI_TRUE or JNI_FALSE. ReleaseStringChars either frees the copy or unpins the instance, depending upon whether GetStringChars has returned a copy or not.

I am correct in assuming this is a bug in Gordon's book?

Flavio
  • 11,925
  • 3
  • 32
  • 36
Edward Loper
  • 15,374
  • 7
  • 43
  • 52

1 Answers1

67

Yes, your assumption is correct (you should always call ReleaseStringUTFChars).

Brett Kail
  • 33,593
  • 2
  • 85
  • 90
  • What happen does if it will not be called ? – Bulma Dec 12 '17 at 03:42
  • 2
    Memory will be leaked (the JVM will believe that you need the memory indefinitely). – Brett Kail Dec 12 '17 at 13:21
  • 2
    Sure ! But why we don't have free allocated memory function for another data types such as : int, double . It should be RealseInt(arg,arg), ReleaseDouble(arg,arg)...or something like that ? – Bulma Dec 13 '17 at 02:00
  • 4
    Int and double aren't variable-length like strings, so the data can be trivially copied to the caller. (It's probably best to create a new question rather than continuing a conversation on a 6-year-old answer.) – Brett Kail Dec 13 '17 at 03:02
  • Please clarify. I read that arbitrary arguments are passed as pass by mechanism method from Java to C as local reference. If yes, then it would be eventually cleaned up as soon as native method execution is done, and there wont be memory leak right? – Vidz Jul 13 '22 at 06:34
  • @Vidz It's probably best to open a new question. It's a local reference only: the JNI cannot know whether you're holding the `char *` beyond the end of the JNI method. – Brett Kail Jul 14 '22 at 12:09