Search code examples
javaandroidandroid-ndkjava-native-interface

JNI function crash when declare large arrays


Currently I've written a JNI function inside Android Studio project and the app is crashed at this line of JNI function.

rgbStruct values[1700][1700];

while the rgbStruct is

struct rgbStruct {
  unsigned char r, g, b;
}

The error message is A/libc: Fatal signal 11 (SIGSEGV), code 2, fault addr 0xbf06f37c in tid 11351

Interestingly, rgbStruct values[1500][1500]; works fine though. So I guess this would be a memory leak issue and I'm not sure how I can increase this memory limit of native side. I've already tried to increase the memory size from studio.vmpoptions file and it doesn't help at all. Please let me know what I can do for this.

At studio.vmoptions

-Xmx8000m
-XX:MaxPermSize=4024m
-XX:ReservedCodeCacheSize=2000m
-XX:+UseCompressedOops

For code reference:

extern "C" JNIEXPORT jstring JNICALL Java_com_test_MainActivity_funcFromJNI(
        JNIEnv * env, jobject  obj) {
    rgbStruct pixels[1700][1700];
    return env->NewStringUTF("Hello");
}

Solution

  • Yeah, you can't do this that way. What you've done is declare a local variable with a size of about 7MB inside a C function. The runtime will try to allocate this on the stack, not the heap. This won't work.

    You need to allocate the memory for that dynamically, on the heap, using malloc or something similar. Read up on how to dynamically allocate memory when using JNI.