6

以下是我编写的 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))
          )
4

1 回答 1

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);
}
于 2013-05-07T04:53:19.647 回答