几乎相同的函数,但只有一些除以0错误

给出了一个简单的矩阵 – 矩阵元素划分功能.但是,运行int8& int16版本返回整数除以valgrind的0错误,&来自命令行的seg故障. int32,spfp和dpfp函数,我确保除了类型声明之外是相同的文本,没有这个问题.矩阵中的值随rand()函数随机生成.为什么只有部分返回除以0错误?

第一功能

double matrix_matrix_div_elementwise_int8(int size,int threads)
{
//initialize index variables, random number generator, and timer
int i;
int size2D=size*size;
srand(SEED);
struct TIME_STRUCT start,end;

//allocate memory for matrices
INT8_TYPE *A=malloc(sizeof(INT8_TYPE)*(size*size));
INT8_TYPE *B=malloc(sizeof(INT8_TYPE)*(size*size));
INT8_TYPE *C=malloc(sizeof(INT8_TYPE)*(size*size));

//initialize input matrices to random numbers
//initialize output matrix to zeros
for(i=0;i<(size*size);i++)
{
    A[i]=rand();
    B[i]=rand();
    C[i]=0;
}

//serial operation
if(threads==1)
{
    //start timer
    TIME_GET(&start);
    //computation
    for(i=0;i<size2D;i++)
    {
        C[i]=A[i]/B[i];
    }
    //end timer
    TIME_GET(&end);
}
//parallel operation
else
{
    //start timer
    TIME_GET(&start);
    //parallelize with OpenMP
    #pragma omp parallel for num_threads(threads) private(i)
    //computation
    for(i=0;i<size2D;i++)
    {
        C[i]=A[i]/B[i];
    }
    //end timer
    TIME_GET(&end);
}

//free memory
free(C);
free(B);
free(A);

return TIME_RUNTIME(start,end);
} 

第二功能

double matrix_matrix_div_elementwise_int32(int size,int threads)
{
//initialize index variables, random number generator, and timer
int i;
int size2D=size*size;
srand(SEED);
struct TIME_STRUCT start,end;

//allocate memory for matrices
INT32_TYPE *A=malloc(sizeof(INT32_TYPE)*(size*size));
INT32_TYPE *B=malloc(sizeof(INT32_TYPE)*(size*size));
INT32_TYPE *C=malloc(sizeof(INT32_TYPE)*(size*size));

//initialize input matrices to random numbers
//initialize output matrix to zeros
for(i=0;i<(size*size);i++)
{
    A[i]=rand();
    B[i]=rand();
    C[i]=0;
}

//serial operation
if(threads==1)
{
    //start timer
    TIME_GET(&start);
    //computation
    for(i=0;i<size2D;i++)
    {
        C[i]=A[i]/B[i];
    }
    //end timer
    TIME_GET(&end);
}
//parallel operation
else
{
    //start timer
    TIME_GET(&start);
    //parallelize with OpenMP
    #pragma omp parallel for num_threads(threads) private(i)
    //computation
    for(i=0;i<size2D;i++)
    {
        C[i]=A[i]/B[i];
    }
    //end timer
    TIME_GET(&end);
}

//free memory
free(C);
free(B);
free(A);

return TIME_RUNTIME(start,end);

}

最佳答案
如果B [i]为0,则会出现除零问题. rand()可以返回0.

所以有时B [i] = rand();将0分配给B [i].

正如评论中所述,这将更少见,因为0更可能是rand()操作的结果.

转载注明原文:几乎相同的函数,但只有一些除以0错误 - 代码日志