title: Heap Corruption - SEGV_MAPERR in Android Native code
body: <p>I am trying to create a small library for stream AES encryption, I started my work based on Facebook Conceal project (<a href="https://github.com/facebook/conceal" rel="nofollow">https://github.com/facebook/conceal</a>), just changing some things and improving the wrapper around the native to support ciphers with padding.</p>
  
  <p>It is working and it can decipher files without problems but I get random Heap Memory Corruptions when I work with large streams, and after a lot of time debugging I have been unable to find the error.</p>
  
  <p>Here is my code:<br>
  <a href="https://gist.github.com/frisco82/9782725" rel="nofollow">https://gist.github.com/frisco82/9782725</a></p>
  
  <p>I have tried to find memory allocation or free problems but there are almost no malloc or free, and jni call should be safe, the same goes for openssl ones (I have compiled my own but conceal provided ones also fail)</p>
  
  <p>CheckJni does not warn about anything and while the context handling is a bit out of the box it doesn't seem broken (indeed Android conscrypt seems to use something similar).</p>
  
  <p>Also if someone can point me to a Android native AES multistep (multiple update calls) library I will switch to that and forget this.</p>
  
  <p>The error varies from time to time but it is usually similar to his:</p>
  
  <pre><code>03-26 10:33:02.065: A/dalvikvm(2475): @@@ ABORTING: DALVIK: HEAP MEMORY CORRUPTION IN mspace_malloc addr=0x0
  03-26 10:33:02.065: A/libc(2475): Fatal signal 11 (SIGSEGV) at 0xdeadbaad (code=1), thread 2494 (AsyncTask #1)
  03-26 10:33:02.205: I/DEBUG(933): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
  03-26 10:33:02.205: I/DEBUG(933): Build fingerprint: 'generic_x86/google_sdk_x86/generic_x86:4.4.2/KK/999428:eng/test-keys'
  03-26 10:33:02.205: I/DEBUG(933): Revision: '0'
  03-26 10:33:02.205: I/DEBUG(933): pid: 2475, tid: 2494, name: AsyncTask #1  &gt;&gt;&gt; com.proton &lt;&lt;&lt;
  03-26 10:33:02.205: I/DEBUG(933): signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr deadbaad
  </code></pre>
  
  <p>Full stack traces: <br/>
  <a href="http://pastebin.com/f6mDuQEj" rel="nofollow">http://pastebin.com/f6mDuQEj</a></p>