title: GetByteArrayRegion causes ArrayIndexOutOfBoundsException
body: <p>I'm trying to decode Speex encoded audio files using Speex library but I always get <code>ArrayIndexOutOfBoundsException</code></p>
  
  <pre><code>JNIEXPORT jint JNICALL Java_com_app_shared_Speex_decode
      (JNIEnv *env, jobject obj, jbyteArray encoded, jshortArray lin, jint size) {
  
          jbyte buffer[dec_frame_size ];
          jshort output_buffer[dec_frame_size ];
          jsize encoded_length = size;
  
          if (!codec_open)
              return 0;
  
          env-&gt;GetByteArrayRegion(encoded, rtp_header, encoded_length, buffer);
  
          /*  
          jboolean isCopy;
          jbyte* data = env-&gt;GetByteArrayElements(encoded, &amp;isCopy);
          if(isCopy){
          memcpy(buffer, data, encoded_length);               
          env-&gt;ReleaseByteArrayElements(encoded, data, JNI_ABORT);
          }
          */
  
          speex_bits_read_from(&amp;dbits, (char *)buffer, encoded_length);
          speex_decode_int(dec_state, &amp;dbits, output_buffer);
  
          std::string bufStr;
  
          for(int i=0; i&lt;20; i++){
              char buff[100];
              sprintf(buff, "Speex test %d =&gt; %d", i, output_buffer[i]);
              bufStr = buff;
              LOGI(bufStr.c_str());
          }
  
          bufStr = "before SetShortArrayRegion";
          LOGI(bufStr.c_str());
  
          (env)-&gt;SetShortArrayRegion(lin, rtp_header, dec_frame_size, output_buffer);
  
          bufStr = "after SetShortArrayRegion";
          LOGI(bufStr.c_str());
  
          return (jint)dec_frame_size;            
  }
  </code></pre>
  
  <p>I get:</p>
  
  <pre><code>SharedSpeex before SetShortArrayRegion
  dalvikvm    JNI WARNING: JNI method called with exception pending
  dalvikvm              in Lcom/company/shared/Speex;.decode:([B[SI)I (SetShortArrayRegion)
  dalvikvm    Pending exception is:
  dalvikvm    java.lang.ArrayIndexOutOfBoundsException: [B offset=12 length=1634 src.length=1634
  </code></pre>
  
  <p>The interesting point is that if I fully comment the line containing <code>SetShortArrayRegion</code>, the exception happens upon exiting the scope:</p>
  
  <pre><code>SharedSpeex       before SetShortArrayRegion
  SharedSpeex       after SetShortArrayRegion
  AndroidRuntime    Shutting down VM
  dalvikvm          threadid=1: thread exiting with uncaught exception (group=0xa62ca288)
  AndroidRuntime    FATAL EXCEPTION: main
  AndroidRuntime    java.lang.ArrayIndexOutOfBoundsException: [B offset=12 length=1634 src.length=1634
  </code></pre>
  
  <p>It's while in the official <a href="http://developer.iristed.com/training/articles/perf-jni.html" rel="nofollow">JNI</a> documention it clearly prefers <code>GetByteArrayRegion</code> instead of <code>GetByteArrayElements</code> because of:</p>
  
  <ul>
  <li>Reduces the risk of programmer error — no risk of forgetting to call Release after something fails.</li>
  </ul>