我正在尝试使用2D数组和MPI_Scatterv。当我调用MPI_Scatterv时,我得到了
================================================================================
= 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的错误。我不能使用线性化的2D数组,因此我无法创建像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();
}
如果我在rxMatrix
之后打印MPI_Scatterv
,程序将打印Rank0子矩阵,然后崩溃并出现分段错误。我哪里错了?
答案 0 :(得分:0)
如果未正确初始化txMatrix
,则此表达式将调用未定义的行为。
&txMatrix[0][0]
虽然MPI_Scatterv
的第一个参数在非根级别*上无关紧要,但仅评估表达式会导致段错误。只需对root / nonroot使用if / else,并为后者传递NULL
。
*:至少根据标准,我已经看到这在MPI实现中被窃听。