[Rcpp-devel] Segfault, is it because of iterators/pointers?

Alessandro Mammana mammana at molgen.mpg.de
Tue Feb 11 15:18:23 CET 2014


Hi all,
I got another segfault using Rcpp. It is very difficult to understand
where it happens and to reduce it to a minimal example, so for now I
am not posting very precise code here, but I have a suspicion, maybe
you could help me saying if my suspect is right.

I am doing something similar:

in a .cpp file:
@@@@@@@@@@@@@@@@@@@
struct GapMat {
    int* ptr;
    int* colset;
    int nrow;
    int ncol;


    inline int* colptr(int col){
        return ptr + colset[col];
    }

    GapMat(){}

    GapMat(int* _ptr, int* _colset, int _nrow, int _ncol):
        ptr(_ptr), colset(_colset), nrow(_nrow), ncol(_ncol){}
};


// [[Rcpp::export]]
IntegerVector colSumsGapMat(Rcpp::IntegerVector vec,
Rcpp::IntegerVector pos, int nrow){
   GapMat mat(vec.begin(), pos.begin(), nrow, pos.length());
   IntegerVector res(pos.length());

    for (int i = 0; i < pos.length(); ++i){
        for (int j = 0; j < nrow; ++j){
            res[i] += mat.colptr(i)[j];
        }
    }

    return res;
}
@@@@@@@@@@@@@@@@@@@@@

from R:

vec <- a very big integer vector
nrow <- 80
pos <- a very big subset of positions, such that max(pos) + nrow < length(vec)
colsums <- colSumsGapMat(vec, pos, nrow)


from time to time I get a segfault.
Note: this is not exactly the code that produces the segfault (because
that one is very complicated), so it might be that this code is
totally fine.

My suspicion:

I am using the pointer "vec.begin()", but then I am allocating new
memory in the R area of memory with "IntegerVector res(pos.length())"
and R decides to move the original values of "vec" to some other
place, making the pointer invalid.

Is that possible????

Sorry for being very vague and thx in advance!!!
Ale

-- 
Alessandro Mammana, PhD Student
Max Planck Institute for Molecular Genetics
Ihnestraße 63-73
D-14195 Berlin, Germany


More information about the Rcpp-devel mailing list