为什么这个Rcpp代码在使用两个push_back时会崩溃?

问题描述 投票:0回答:1

这是我的代码的简化版本:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
List test_bug(int N) {

    std::vector<int>    inds;
    std::vector<double> vals;

    for (int k = 0; k < N; k++) {
        int i_k = k;
        double x_k = k;
        inds.push_back(i_k);
        vals.push_back(x_k);
    }

    return List::create(wrap(inds), wrap(vals));
}

/*** R
for (k in 1:100) {
    test <- test_bug(1000000)
}
*/

这会崩溃。但只有当使用 2 个

push_back()
时(一个看起来不错)。 当我删除
return
并将返回类型更改为
void
时,它也不再崩溃。

我完全不明白发生了什么;任何帮助,将不胜感激。 谢谢


均开启:

  • 带有 R v4.2.2 和 Rcpp v1.0.10 的 Windows 10
  • AlmaLinux 8.8,带有 R v4.2.3 和 Rcpp v1.0.11
rcpp
1个回答
0
投票

似乎在这里工作。

您的代码,添加了条件
print

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
List test_bug(int N) {

    std::vector<int>    inds;
    std::vector<double> vals;

    for (int k = 0; k < N; k++) {
        int i_k = k;
        double x_k = k;
        inds.push_back(i_k);
        vals.push_back(x_k);
    }

    return List::create(wrap(inds), wrap(vals));
}

/*** R
for (k in 1:100) {
    if (k %% 10 == 0) print(k)
    test <- test_bug(1000000)
}
*/

输出

$ Rscript -e 'Rcpp::sourceCpp("question.cpp")'

> for (k in 1:100) {
+     if (k%%10 == 0) 
+         print(k)
+     test <- test_bug(1e+06)
+ }
[1] 10
[1] 20
[1] 30
[1] 40
[1] 50
[1] 60
[1] 70
[1] 80
[1] 90
[1] 100
$ 
© www.soinside.com 2019 - 2024. All rights reserved.