title: JNI: How to delete a local reference c++
body: <p>For improving the performance of my android app i decided to re write calculation parts in c++ and use JNI. here is the problem :</p>
  
  <p>My c++ method generates very large amount of objects (2k to 10k) in a multiple level loop. An object is being created in the deepest level and stored in a vector of jobject's for the later return. My implementation of the last part is as below:</p>
  
  <pre><code>jobject genObj = env-&gt;NewObject(jclass,jmethodId,...);
  Vector.push_back(genObj);
  env-&gt;DeleteLocalRef(genObj);
  </code></pre>
  
  <p>this code gives me: </p>
  
  <p><strong><em>JNI ERROR (app bug): accessed stale local reference</em></strong></p>
  
  <p>Which means im trying to access a deleted block of memory. This is unexpected because push_back should copy the argument not its pointer.</p>
  
  <p>What should i do ?</p>
  
  <p>Ps: not deleting the local ref will lead to localref table overflow</p>