Gilfoyle
Gilfoyle

Reputation: 3636

MPI Segmentationi fault MPI_Scatter using C

I am new in this area and use OpenMPI and C. I try to find out why my code leads to an Segmentatioin fault. I red already a lot about MPI but I did not find any help. It took me already hours. So I decided to ask here for help.

I get the expected result of my code. But I also get every time an error message.

Is it right how I use MPI_Scatter in my case?

Here is my simple code:

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

const int MASTER_RANK = 0;
#define DIM 3

int main(int argc, char* argv[])
{
    int numProc, rank;

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

    int n = 9;
    double *m;
    double *m_client;
    m_client = (double *)malloc(3);

    if(rank == MASTER_RANK)
    {
        m = (double* )malloc(n);
        for(int i=0; i<n; i++)
        {
            m[i] = (double)i+1.0;
        }
    }

    MPI_Scatter(m, 3, MPI_DOUBLE, m_client, 3, MPI_DOUBLE, MASTER_RANK, MPI_COMM_WORLD);

    printf("Process %d:\n", rank);
    for(int i=0; i < 3; i++)
    {
        printf(" (%lf", m_client[i]);
        m_client[i] += 1000*rank;
        printf(" -> %lf)", m_client[i]);
        printf("\n");
    }
    printf( "\n" );

    MPI_Gather(m_client, 3, MPI_DOUBLE, m, 3, MPI_DOUBLE, MASTER_RANK, MPI_COMM_WORLD);

    if(rank == MASTER_RANK)
    {
        printf("Master: Received= \n");
        for(int i=0; i<numProc; i++)
        {
            for(int j=0; j < 3; j++)
            {
                int idx = i*3 + j;
                printf("%lf ", m[idx]);
            }
            printf("from Process %d\n", i);
        }
    }
    free(m);
    free(m_client);
    MPI_Finalize();
    exit(0);
}

I build my MPI file by using mpicc mpifile.c -o mpifile and run it with mpirun -np 3 ./mpifile. I use 3 processes.

The error I get is:

[Samuel-Z97-HD3:14361] *** Process received signal ***
[Samuel-Z97-HD3:14361] Signal: Segmentation fault (11)
[Samuel-Z97-HD3:14361] Signal code:  (128)
[Samuel-Z97-HD3:14361] Failing at address: (nil)

I am using Ubuntu and vim / Geany.

Upvotes: 0

Views: 289

Answers (1)

Donghui Zhang
Donghui Zhang

Reputation: 1133

Your code has two problems.

  • Both your malloc() calls are having wrong sizes. You should allocate number of bytes instead of number of doubles. E.g. instead of calling malloc(3), call malloc(3*sizeof(double)).
  • Another problem is that your variable m should be initialized to NULL. Alternatively, you could surround free(m) with if(rank == MASTER_RANK). As is, a non-master process calls free(m) where m is uninitialized and could contain arbitrary value.

Upvotes: 1

Related Questions