title: caught segfault, memory not mapped error in Rcpp trying to implement a function
body: <p>i'm new in Rcpp and i dont really know Rcpp. but as a personal project, i was trying to run some sort algorithms using some C code that i had, converting them to R with Rcpp.</p>
  
  <p>But i'm getting the memory not mapped error, and i dont really understand what i'm doing wrong, so if someone could enlighten me :)</p>
  
  <p>The problem happens when a try the following code</p>
  
  <pre><code>#include &lt;Rcpp.h&gt;
  using namespace Rcpp;
  
  void intercala(int p, int q, int r, NumericVector v)
  {
    int i, j, k;
    NumericVector w = NumericVector::create();
  
     i = p;
     j = q;
     k = 0;
  
  
     while (i &lt; q &amp;&amp; j &lt; r) {
        if (v[i] &lt; v[j]) {
           w[k] = v[i];
           i++;
        }
        else {
           w[k] = v[j];
           j++;
        }
        k++;
     }
     while (i &lt; q) {
        w[k] = v[i];
        i++;
        k++;
     }
     while (j &lt; r) {
        w[k] = v[j];
        j++;
        k++;
     }
     for (i = p; i &lt; r; i++)
        v[i] = w[i-p];
  }
  
  void mergesort(int p, int r, NumericVector v)
  {
     int q;
     if (p &lt; r - 1) {
        q = (p + r) / 2;
        mergesort(p, q, v);
        mergesort(q, r, v);
        intercala(p, q, r, v);
     }
  }
  
  // [[Rcpp::export]]
  NumericVector mergesortC(NumericVector vetor) {
    int n = vetor.size();
    mergesort(0,n,vetor);
    return vetor;
  }
  </code></pre>
  
  <p>This code is in a file called merge.cpp</p>
  
  <p>Them when i try to run on R</p>
  
  <pre><code>    &gt; library(Rcpp)
      &gt; sourceCpp("merge.cpp")
      &gt; vetor&lt;-sample(1:10)
      &gt; vetor
       [1]  1  5  7  4  3  8  9  2 10  6
      &gt; mergesortC(vetor)
       [1]  1  2  3  4  5  6  7  8  9 10
      &gt; vetor
  
       *** caught segfault ***
      address 0x8, cause 'memory not mapped'
  
      Possible actions:
      1: abort (with core dump, if enabled)
      2: normal R exit
      3: exit R without saving workspace
      4: exit R saving workspace
      Selection: 
  </code></pre>
  
  <p>It seems to me that i'm doing something that i shouldn't, but the code seem to work in the begin, then i somehow mess with the memory in the object vetor. I managed to work on other algorithms with Rcpp, but this one wont work, and i dont understand what i'm doing wrong, so if anyone could spare a moment.</p>