Dejan Skledar
Dejan Skledar

Reputation: 11435

MPI_Scatter doesn't work right

I am trying to write a program, which calculates with 4 nodes and the function MPI_Scatter the sum of first N numbers.

The program asks for the number, that each node should calculate (for example if you put in 5, the master will create an array sized 20, and each node will calculate the sum of 5 numbers), and then return it back to the master. At last the master then calculates the sum of all returned values (with MPI_Gather).

node0 -> 1+2+3+4+5 = 15

node1 -> 6+7+8+9+10 = 40

...

node0 -> 15 + 40 + ...

You get the point.

I'm stuck at the MPI_Scatter function - It just doesn't work correctly...

I get the error:

"Error in malloc 3: Cannot allocate memory"

My code:

#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;
}

Upvotes: 2

Views: 1291

Answers (1)

wolfPack88
wolfPack88

Reputation: 4203

The reason you are getting this error is when you call the line int *procRow = malloc(sizeof(int) * input);, only rank 0 has a valid value for input. All other ranks do not know what the user has input, and input is uninitialized, making its use in malloc undefined behavior. Replace your MPI_Barrier command with the line MPI_Bcast(&input, 1, MPI_INT, 0, MPI_COMM_WORLD);, and your code should work.

Upvotes: 4

Related Questions