R调用的C代码不断崩溃 [英] C code called by R keeps crashing
问题描述
以下是我编写的 C 代码的一部分.函数 foo
将在 R 中调用.代码不断导致 R 崩溃,我将问题缩小到这个 outer()
函数,它用于计算外和或差.注意被注释掉的部分:如果我不注释掉它,如果每个数组包含超过 1000 个数据点,函数将导致 R 崩溃.如果我将其注释掉,我可以毫无问题地计算明显更长的数组的外部和/差(例如,每个数组超过 100000 个数据点).我想知道问题是什么...谢谢!
Below is part of a C code I wrote. The function foo
is to be called in R. The code keeps causing R to crash, and I narrowed down the problem to this outer()
function, which is used to compute outer sum or difference. Note the part that is commented out: If I do not comment it out, the function will lead R to crash if each of the arrays contains, say, over 1000 data points. If I comment it out, I can compute outer sum/difference for significantly longer arrays with no problem (e.g, over 100000 data points per array). I wonder what the problem is... Thank you!
#include <R.h>
#include <Rmath.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
void outer(double *x1, double *x2, int *n, int operation, double *output){
int i, j;
if(operation==1){
for(i=0; i<*n; i++){
for(j=0; j<*n; j++){
output[(*n)*i+j]=x1[j]+x2[i];
}
}
} else if(operation==2){
for(i=0; i<*n; i++){
for(j=0; j<*n; j++){
output[(*n)*i+j]=x1[j]-x2[i];
//Rprintf("%d ", (*n)*i+j); //<-----------HERE
}
}
}
}
void foo(double *x, double *y, int *npred, int *nsamp){
int oper=2;
double xouter[*nsamp], youter[*nsamp];
double outer_temp_x[(*nsamp)*(*nsamp)], outer_temp_y[(*nsamp)*(*nsamp)];
outer(x, x, nsamp, oper, &outer_temp_x[0]);
outer(y, y, nsamp, oper, &outer_temp_y[0]);
}
//编译代码后,我在R中使用下面的代码来调用函数:
//After compiling the code, I use the code below in R to call the function:
dyn.load("foo.so")
x=as.matrix(rnorm(10000))
y=rlnorm(10000)
invisible(.C("foo",
x=as.double(as.vector(x)),
y=as.double(y),
npred=as.integer(ncol(x)),
nsamp=as.integer(length(y))
)
推荐答案
我认为这是超出堆栈并造成麻烦.
I think it is overunning the stack and causing trouble.
试试这个:
void foo(double *x, double *y, int *npred, int *nsamp){
int oper=2;
double xouter[*nsamp], youter[*nsamp];
// The prior code allocated on the stack. Here, we make a pair of calls
// to 'malloc' to allocate memory for the arrays. This gets memory from
// the heap. The stack is fairly limited, but the heap is huge.
// 'malloc' returns a pointer to the allocated memory.
double* outer_temp_x=malloc(sizeof(double)*(*nsamp)*(*nsamp));
double* outer_temp_y=malloc(sizeof(double)*(*nsamp)*(*nsamp));
outer(x, x, nsamp, oper, &outer_temp_x[0]);
outer(y, y, nsamp, oper, &outer_temp_y[0]);
// The downside of allocating on the heap, is that you must release the
// memory at some point. Otherwise you have what's called a "memory leak."
// 'free' is the function to free the memory, and it is called on the
// pointer value returned by 'malloc'.
free(outer_temp_x);
free(outer_temp_y);
}
这篇关于R调用的C代码不断崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!