NewStringUTF()/DeleteLocalRef() produces JNI ERROR (app bug): accessed stale Local

Viewed 40

This may be related to JNI ERROR (app bug): accessed stale local reference 0x2d when delete a local reference in native method, however that question received no answers.

I had Android Studio generate a skeletal "Native C++" app and then modified native-lib.cpp as follows:

#include <jni.h>
#include <string>

extern "C" JNIEXPORT jstring JNICALL
Java_com_example_jnitest_MainActivity_stringFromJNI(JNIEnv* env, jobject /* this */)
{
    jstring jniHeader = env->NewStringUTF("x-foo");
    env->DeleteLocalRef(jniHeader);    // FAILS HERE
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}

When I step through this in the debugger, I get this error:

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()

Are you not supposed to call DeleteLocalRef() on strings? The docs don't say.

I tried using PushLocalFrame()/PopLocalFrame() instead, and still got the same results.

I tried creating a global reference and that only changed the error to JNI ERROR (app bug): accessed stale Global 0x2a52


Additional information:

  • Android emulator is running API 30
  • build.gradle specifies compileSdkVersion 29, targetSdkVersion 28, minSdkVersion 28.
  • Android studio 4.2.2, Runtime version 11.0.8+10-b944.6916264 x86_64
  • This is on a Mac
1 Answers

I believe this is a bug in the Android Studio debugger and/or the JVM. My code is correct as written, but throws an error if you single-step through it in the debugger.

Leaving the question open in case someone has more to add, or a fix for the problem.

Related