gpt4 book ai didi

R调用的C代码不断崩溃

转载 作者:太空狗 更新时间:2023-10-29 17:22:15 24 4
gpt4 key购买 nike

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

最佳答案

我认为它超出了堆栈并造成了麻烦。

试试这个:

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代码不断崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16411397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com