我正在尝试使用 OpenMP 实现具有动态内存分配的矩阵乘法。我设法让我的程序编译得很好,但是当我试图执行它时,我得到 ./ line 14: 17653 Segmentation fault (core dumped) ./matrix.exe $matrix_size
int main(int argc, char *argv[]){
if(argc < 2){
printf("Usage: %s matrix/vector_size\n", argv[0]);
return 0;
}
int size = atoi(argv[1]);
double **matrix2 = (double **)malloc(sizeof(double*)*size);
double **matrix = (double **)malloc(sizeof(double*)*size);
double **result_sq = (double **)malloc(sizeof(double*)*size);
double **result_pl = (double **)malloc(sizeof(double*)*size);
int t;
for (t =0; t<size; t++) {
matrix[t]= (double *)malloc(sizeof(double)*size);
matrix2[t]= (double *)malloc(sizeof(double)*size);
result_pl[t]= (double *)malloc(sizeof(double)*size);
result_sq[t]=(double *)malloc(sizeof(double)*size);
}
matrix_vector_gen(size, matrix, matrix2);
我相信我使用 malloc 和双指针的方式导致了这个错误。
此外,该程序包含以下函数,用于生成两个矩阵并按顺序执行一次乘法运算,并使用 openMP 执行一次乘法运算。
void matrix_vector_gen(int size, double **matrix, double **matrix2){
int i,j;
for(i=0; i<size; i++)
for(j=0; j<size*size; j++)
matrix[i][j] = ((double)rand())/5307.0;
matrix2[i][j] = ((double)rand())/65535.0;
}
void matrix_mult_sq(int size, double **matrix2,
double **matrix_in, double **matrix_out){
int i, j, k;
for(i=0; i<size; i++){
for(j=0; j<size; j++)
matrix_out[i][j] = 0.0;
for(k=0; k<size; k++)
matrix_out[i][j] += matrix_in[i][k] * matrix2[k][j];
}
}
void matrix_mult_pl(int size, double **matrix2,
double **matrix_in, double **matrix_out){
int i, j, k;
# pragma omp parallel \
shared(size, matrix2, matrix_in, matrix_out) \
private(i,j,k)
# pragma omp for
for(i=0; i<size; i++){
for(j=0; j<size; j++)
matrix_out[i][j] = 0.0;
for(k=0; k<size; k++)
matrix_out[i][j] += matrix_in[i][k] * matrix2[k][j];
}
}