Why is my Rcpp function that returns a vector <vector <int>> crashing?

StackOverflow https://stackoverflow.com/questions/23173860

  •  06-07-2023
  •  | 
  •  

سؤال

Here is my test code

#include <Rcpp.h>
using namespace Rcpp;

#include "/Users/jjunju/Documents/R/accum/accum.h"

// Below is a simple example of exporting a C++ function to R. You can
// source this function into an R session using the Rcpp::sourceCpp 
// function (or via the Source button on the editor toolbar)

// For more on using Rcpp click the Help button on the editor toolbar

// [[Rcpp::export]]
int timesTwo(int x) {
   return x * 2;
}

// [[Rcpp::export]]
void testExternalHeader(){
  matrix <int> test(3,3);
  test.Print();
}

// [[Rcpp::export]]
vector<vector <int> > testVector(){
  vector<vector <int> > a;
  a.resize(3); //rows
  for(int i=0;i<3;i++){
    a.resize(3); //cols
    for(int j=0;j<3;j++){
    a[i][j]=i*3+j;
    }
  }
  return(a);
}

Here is a a picture of my Rstudio session. You can see that my function testVector crashes Rstudio. I don't have problems with any other functions from my external header. Just this one!! :(Rstudio Session that crashed

هل كانت مفيدة؟

المحلول

Your vector a contains 3 empty vectors, but you treat them as if they were not here:

a[i][j]=i*3+j; // a[i] has size 0 here

This out of bounds access is undefined behaviour. The reason is that this

a.resize(3); //cols

is not dong what you think it is. It essentially has no effect, because a is already size 3 at this stage.

If you want a 3 by 3 vector of vectors, initialize a like this:

vector<vector <int> > a(3, std::vector<int>(3));
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top