C MPI#u散射不';我不能正常工作

C MPI#u散射不';我不能正常工作,c,mpi,scatter,C,Mpi,Scatter,我正在写一个程序,它用4个节点和函数MPI_计算前N个数的和 程序要求每个节点计算的数字(例如,如果输入5,主节点将创建一个大小为20的数组,每个节点将计算5个数字的总和),然后将其返回给主节点。最后,主节点计算所有返回值的总和(使用MPI_聚集) 节点0->1+2+3+4+5=15 节点1->6+7+8+9+10=40 节点0->15+40+ 你明白了 我被MPI_分散功能卡住了-它不能正常工作 我得到一个错误: “malloc 3中的错误:无法分配内存” 我的代码: #include &l

我正在写一个程序,它用4个节点和函数MPI_计算前N个数的和

程序要求每个节点计算的数字(例如,如果输入5,主节点将创建一个大小为20的数组,每个节点将计算5个数字的总和),然后将其返回给主节点。最后,主节点计算所有返回值的总和(使用MPI_聚集)

节点0->1+2+3+4+5=15

节点1->6+7+8+9+10=40

节点0->15+40+

你明白了

我被MPI_分散功能卡住了-它不能正常工作

我得到一个错误:

“malloc 3中的错误:无法分配内存”

我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mpi.h>

int *createArray (int st_proc, int input) {
    int *array;
    array = malloc(input*st_proc*sizeof(int));
    int i;
    for (i=0; i<input*st_proc; i++) {
        array[i] = i+1;
    }

    return array;
}

void printArray (int *row, int nElements) {
    int i;
    for (i=0; i<nElements; i++) {
        printf("%d ", row[i]);
    }
    printf("\n");
}

int main (int argc, char **argv) {

    MPI_Init(&argc, &argv);
    int nproc, id;
    MPI_Comm_size(MPI_COMM_WORLD, &nproc); // Get number of processes
    MPI_Comm_rank(MPI_COMM_WORLD, &id); // Get own ID

    int *array;
    int input;
    if (id == 0) {
        printf("Vnesi stevilo: \n");
        scanf("%d",&input);
        array = createArray(nproc, input); // Master process creates matrix
        printf("Initial matrix:\n");
        printArray(array, input*nproc);
    }
    MPI_Barrier(MPI_COMM_WORLD);
    int *procRow = malloc(sizeof(int) * input); // received row will contain input integers
    if (procRow == NULL) {
        perror("Error in malloc 3");
        exit(1);
    }

    if (MPI_Scatter(array, input, MPI_INT, // send one row, which contains input integers
                procRow, input, MPI_INT, // receive one row, which contains input integers
                0, MPI_COMM_WORLD) != MPI_SUCCESS) {

        perror("Scatter error");
        exit(1);
    }

    printf("Process %d received elements: ", id);
    printArray(procRow, input);

    MPI_Finalize();

    return 0;
}
#包括
#包括
#包括
#包括
int*createArray(int stu proc,int input){
int*数组;
数组=malloc(输入*st_proc*sizeof(int));
int i;

对于(i=0;i出现此错误的原因是调用行
int*proclow=malloc(sizeof(int)*input)
,只有秩0对
输入具有有效值。所有其他秩不知道用户输入了什么,并且
输入
未初始化,在
malloc
未定义的行为中使用它。将
MPI\u Barrier
命令替换为行
MPI\u Bcast(&input,1,MPI\u INT,0,MPI\u COMM\u WORLD)
,你的代码应该可以工作。

你有内存泄漏,在你不再需要它之后,或者在
返回0
之前,释放
数组
proclow
;是的,我知道,我出于某种原因删除了它。对这个问题太失望了……我的目标就是这个方向,其他级别无法访问input、 .但这是一个多么顺利的修复。谢谢你,伙计!