【问题标题】:C - Segmentation fault using Scatterv with dynamic 2D arrayC - 使用具有动态二维数组的 Scatterv 进行分段错误
【发布时间】:2017-11-19 07:04:44
【问题描述】:

我正在尝试使用二维数组和 MPI_Scatterv。当我调用 MPI_Scatterv 我得到 ​​p>

    ================================================================================
    =   BAD TERMINATION OF ONE OF YOUR APPLICATION PROCESSES
    =   PID 5790 RUNNING AT ubuntu
    =   EXIT CODE: 139
    =   CLEANING UP REMAINING PROCESSES
    =   YOU CAN IGNORE THE BELOW CLEANUP MESSAGES
    ================================================================================
YOUR APPLICATION TERMINATED WITH THE EXIT STRING: Segmentation fault (signal 11)
This typically refers to a problem with your application.
Please see the FAQ page for debugging suggestions

如果我使用 C99 2D 数组,它可以工作,但不能使用 malloc。我想知道malloc哪里错了。我不能使用线性化二维数组,所以我不能创建像array[i*columns+j]这样的数组

这是一个测试程序:

int **alloc2d(int n, int m) {
      int i;
      int **array = malloc(n * sizeof(int*));
      array[0] = malloc(n * m * sizeof(int));
      for(i = 1; i < n; i++) 
          array[i] = array[i-1] + m;
      return array;
}

int *genSendc(int dim, int numprocs) {
    int* sendc = (int*)malloc(sizeof(int)*numprocs); 
    int i;
    int subsize = dim/numprocs;
    for(i=0; i<numprocs; ++i)
        sendc[i] = subsize;
    for(i=0; i<dim-subsize*numprocs; ++i)
        sendc[i]+=1;
    return sendc;
}

int *genDispl(int numprocs, int*sendc) {
    int* displ = (int*)malloc(sizeof(int)*numprocs);
    int i;
    displ[0]=0;
    for(i=1; i<numprocs; ++i)
        displ[i] = displ[i-1]+sendc[i-1];
    return displ;
}

int main(int argc, char *argv[]){
    int numprocs, rank, i, j, N=5, M=4;
    int* displMat, *sendcMat;
    int **txMatrix, **rxMatrix;

    MPI_Init(&argc,&argv);
    MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
    MPI_Comm_rank(MPI_COMM_WORLD,&rank);

    sendcMat = genSendc(N, numprocs);
    for(i=0; i<numprocs; ++i)
        sendcMat[i] *= M;
    displMat = genDispl(numprocs, sendcMat);

    rxMatrix = alloc2d(sendcMat[rank]/M, M);
    if (rank == 0) {
        srand(time(NULL));
        txMatrix = alloc2d(N, M);
        for (i=0; i < N; ++i)
            for(j=0; j < M; ++j)
               txMatrix [i][j] = (rand() % 10)+1;
    }

    MPI_Scatterv(&txMatrix[0][0], sendcMat, displMat, MPI_INT, &rxMatrix[0][0], sendcMat[rank], MPI_INT, 0, MPI_COMM_WORLD);

    MPI_Finalize();
}

如果我在MPI_Scatterv 之后打印rxMatrix,程序会打印 Rank0 子矩阵,然后它会因分段错误而崩溃。我哪里错了?

【问题讨论】:

标签: c mpi


【解决方案1】:

如果 txMatrix 未正确初始化,此表达式将调用未定义的行为。

&txMatrix[0][0]

虽然MPI_Scatterv 的第一个参数在非根等级* 上无关紧要,但仅计算表达式可能会导致段错误。只需对 root/nonroot 使用 if/else 并为后者传递 NULL

*:至少按照标准,我已经看到这在 MPI 实现中存在错误。

【讨论】:

  • 即使 txMatrix = NULL 它也不起作用。我需要用 alloc2d 分配它让 Scatter 工作!不知道为什么,我教过 txMatrix 只能被根处理器使用...
猜你喜欢
  • 2014-06-15
  • 2013-09-04
  • 2020-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-07
  • 1970-01-01
相关资源
最近更新 更多