title: NewStringUTF()/DeleteLocalRef() produces JNI ERROR (app bug): accessed stale Local
body: <p>This may be related to <a href="https://stackoverflow.com/questions/45510333/jni-error-app-bug-accessed-stale-local-reference-0x2d-when-delete-a-local-ref">JNI ERROR (app bug): accessed stale local reference 0x2d when delete a local reference in native method</a>, however that question received no answers.</p>
  <p>I had Android Studio generate a skeletal &quot;Native C++&quot; app and then modified native-lib.cpp as follows:</p>
  <pre><code>#include &lt;jni.h&gt;
  #include &lt;string&gt;
  
  extern &quot;C&quot; JNIEXPORT jstring JNICALL
  Java_com_example_jnitest_MainActivity_stringFromJNI(JNIEnv* env, jobject /* this */)
  {
      jstring jniHeader = env-&gt;NewStringUTF(&quot;x-foo&quot;);
      env-&gt;DeleteLocalRef(jniHeader);    // FAILS HERE
      std::string hello = &quot;Hello from C++&quot;;
      return env-&gt;NewStringUTF(hello.c_str());
  }
  </code></pre>
  <p>When I step through this in the debugger, I get this error:</p>
  <pre><code>09-09 17:23:25.371 7512-7512 E/example.jnites: JNI ERROR (app bug): accessed stale Local 0x79  (index 7 in a table of size 7)
  
  [ 09-09 17:23:25.372  7512: 7512 F/example.jnites ]
  java_vm_ext.cc:577] JNI DETECTED ERROR IN APPLICATION: use of deleted local reference 0x79
  java_vm_ext.cc:577]     from java.lang.String  com.example.jnitest.MainActivity.stringFromJNI()
  </code></pre>
  <p>Are you not supposed to call DeleteLocalRef() on strings? The <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/functions.html#NewStringUTF" rel="nofollow noreferrer">docs</a> don't say.</p>
  <p>I tried using <code>PushLocalFrame()</code>/<code>PopLocalFrame()</code> instead, and still got the same results.</p>
  <p>I tried creating a global reference and that only changed the error to <code>JNI ERROR (app bug): accessed stale Global 0x2a52</code></p>
  <hr />
  <p>Additional information:</p>
  <ul>
  <li>Android emulator is running API 30</li>
  <li>build.gradle specifies compileSdkVersion 29, targetSdkVersion 28, minSdkVersion 28.</li>
  <li>Android studio 4.2.2, Runtime version 11.0.8+10-b944.6916264 x86_64</li>
  <li>This is on a Mac</li>
  </ul>