问题
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.
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 :)
The problem happens when a try the following code
#include <Rcpp.h>
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 < q && j < r) {
if (v[i] < v[j]) {
w[k] = v[i];
i++;
}
else {
w[k] = v[j];
j++;
}
k++;
}
while (i < q) {
w[k] = v[i];
i++;
k++;
}
while (j < r) {
w[k] = v[j];
j++;
k++;
}
for (i = p; i < r; i++)
v[i] = w[i-p];
}
void mergesort(int p, int r, NumericVector v)
{
int q;
if (p < 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;
}
This code is in a file called merge.cpp
Them when i try to run on R
> library(Rcpp)
> sourceCpp("merge.cpp")
> vetor<-sample(1:10)
> vetor
[1] 1 5 7 4 3 8 9 2 10 6
> mergesortC(vetor)
[1] 1 2 3 4 5 6 7 8 9 10
> 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:
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.
来源:https://stackoverflow.com/questions/25633615/caught-segfault-memory-not-mapped-error-in-rcpp-trying-to-implement-a-function