【问题标题】:Segmentation fault (core dumped) OpenMP分段错误(核心转储) OpenMP
【发布时间】:2015-05-02 16:46:41
【问题描述】:

我正在尝试使用 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];
      }
    }

【问题讨论】:

  • 您尝试过什么调试代码?也许您添加一些日志记录以查看发生的位置,然后寻求帮助。

标签: pointers malloc openmp double-pointer


【解决方案1】:
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;
}

当您只在循环中执行“for”语句之后的下一个语句时留下大括号时,因此在循环结束后执行“matrix2”行,此时 i 和 j 超出范围,因此 ( double*) matrix2[i] 是垃圾;访问 matrix2[i] 可能会也可能不会导致段错误,具体取决于堆布局,但访问 matrix2[i][j] 很可能会,因为不知道它的去向。

这不是唯一的问题:当您在循环中访问 matrix[i][size*size - 1] 时,matrix[i] 被分配为指向 sizeof(double) * size 数组的指针。

在 C 派生语言中,省略 "if"、"do"、"for"、"case" 和 "while" 语句的大括号通常是个坏主意;想象一下必须添加更多行,这会很麻烦。当代码变得更复杂时,也很难阅读和推理。

【讨论】:

  • 感谢您的建议。在您提到的更改之后,我设法让它工作。
  • @mikebmx1 在这种情况下,您应该考虑接受答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-25
  • 2021-06-03
相关资源
最近更新 更多