由R调用的C代码不断崩溃

时间:2013-05-07 04:48:29

标签: c r crash

以下是我编写的C代码的一部分。函数foo将在R中调用。代码会导致R崩溃,我将问题缩小到此outer()函数,该函数用于计算外部和或差。请注意注释掉的部分:如果我没有注释掉,如果每个数组包含超过1000个数据点,该函数将导致R崩溃。如果我将其评论出来,我可以计算出明显更长的数组的外部和/差异而没有问题(例如,每个数组超过100000个数据点)。我想知道问题是什么......谢谢!

#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中的代码来调用函数:

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))
          )

1 个答案:

答案 0 :(得分:7)

我认为它正在超越堆栈并造成麻烦。

试试这个:

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);
}