(MPI) Segmentation fault with dynamic allocated 2D array

Hi all,
I'm getting segmentation fault errors when I try to send/receive 2 rows of a matrix as a block, and I can't figure out why.

Basically, I have a 4x5 matrix with an extra top row and an extra leftmost column, making it a (4+1)x(5+1) matrix stored in P0. I'm trying to send the 2nd and 3rd row as a block to P1, print out the contents, send the 4th and 5th row as a block to P1, then print out the contents again. I have dynamically allocated a (4+1)x(5+1) memory block to cellblock, then used the pointers cell [i]to point to each "row" of cellblock, so I can access the 2D array by cell[i][j].

I get the correct output, but with segmentation fault at the end.

Here is my code:

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

int main(int argc, char** argv)
{
   int rank, i, j, k = 1;
   int **cell, *row1, *cellblock;
   MPI_Status status;
   MPI_Init(&argc, &argv);
   MPI_Comm_rank(MPI_COMM_WORLD, &rank);
   row1 = (int*)calloc((5+1) * 2, sizeof(int));
   cellblock = (int*)calloc((4+1)*(5+1), sizeof(int));
   cell = &cellblock;
   for (i = 0 ; i < (4+1) ; i++)
        cell = &cellblock[i*(5+1)];
   if (rank == 0)
   {
        for (i = 0 ; i < (4+1) ; i++)
              for (j = 0 ; j < (5+1) ; j++)
                   cell[j] = k++;
        for (i = 1 ; i < 5 ; i+=2)
              MPI_Send(&(cell[0]), (5+1)*2, MPI_INT, 1, 1, MPI_COMM_WORLD);
   }
   if (rank == 1)
   {
        for (i = 0 ; i < 2 ; i++)
        {
            MPI_Recv(row1, (5+1)*2, MPI_INT, 0, 1, MPI_COMM_WORLD, &status);
            for (j = 0 ; j < (5+1)*2 ; j++)
                printf("%d ", row1[j]);
            printf("\n");
       }
   }
   free(row1);
   free(cellblock);
   MPI_Finalize();
   return 0;

}

Please advise. Thank you.

Regards,
Rayne

Firstly, make a backup.

Then remove all the code that refers to arrays of ints and just prove that you can pass a buffer of characters around, effectively an MPI Hello World. Confirm that this cleanly exits.

Then be careful with your type casting whereever there is a void *, for instance the first argument to MPI_Send.

If you want to send 'ints' then change that to a

int *mySendData=&(cell[0]);
MPI_Send(mySendData,.....

and similarly on the read, this lets the compiler do type checking for you.

Also, run the thing under a debugger or use the core dump to find out where the thing is failing. Have you not closed the library down correctly? Is this a build issue? Is it compiler options or selection of libraries?