title: Using MPI_TYPE_VECTOR instead of MPI_GATHER
body: <p>Suppose that <em>k</em> processes compute the elements of a matrix <em>A</em>, whose dimension is <em>(n,m)</em>, where <em>n</em> is the number of rows and <em>m</em> is the number of columns. I am trying to use <code>MPI_GATHER</code> to gather these two matrices to the matrix <em>B</em> at the root process, where the dimension of <em>B</em> is <em>(n,km)</em>. To be more specific, I wrote an example fortran code below. Here, I am passing over the columns of the matrix <em>A</em> (not the entire matrix) to the matrix <em>B</em> but this wouldn't work. When I run the executable using <code>mpirun -n 2 a.out</code>, I get the error:</p>
  
  <p>malloc: *** error for object 0x7ffa89413fb8: incorrect checksum for freed object - object was probably modified after being freed.</p>
  
  <p>1) Why do I get this error message? </p>
  
  <p>2) Who can please explain <em>conceptually</em>, why I have to use <code>MPI_TYPE_VECTOR</code>?</p>
  
  <p>3) How should I correct the <code>MPI_GATHER</code> part of the code? Can I pass over the entire matrix <em>A</em>?</p>
  
  <pre><code>PROGRAM test
  
  IMPLICIT NONE
  
  INCLUDE "mpif.h"
  
  INTEGER, PARAMETER      :: n=100, m=100
  INTEGER, ALLOCATABLE, DIMENSION(:,:)    :: A
  INTEGER, DIMENSION(n,m) :: B
  INTEGER     :: ind_a, ind_c
  INTEGER     :: NUM_PROC, PROC_ID, IERROR, MASTER_ID=0
  INTEGER     :: c
  INTEGER, DIMENSION(m)       :: cvec
  
  CALL MPI_INIT(IERROR)  
  CALL MPI_COMM_RANK(MPI_COMM_WORLD, PROC_ID, IERROR)  
  CALL MPI_COMM_SIZE(MPI_COMM_WORLD, NUM_PROC, IERROR) 
  
  ALLOCATE(A(n,m/NUM_PROC))
  
  DO ind_c=1,m
      cvec(ind_c)=ind_c
  END DO
  
  ! Fill in matrix A
  DO ind_a=1,n    
      DO ind_c=1,m/NUM_PROC
          c=cvec(ind_c+PROC_ID*m/NUM_PROC)    
          A(ind_a,ind_c)=c*ind_a
      END DO
  END DO
  
  ! Gather the elements at the root process          
  DO ind_a=1,n
  
  CALL MPI_GATHER(A(ind_a,:),m/NUM_PROC,MPI_INTEGER,B(ind_a,PROC_ID*m/NUM_PROC+1:(PROC_ID+1)*m/NUM_PROC),m/NUM_PROC,MPI_INTEGER,MASTER_ID,MPI_COMM_WORLD,IERROR)
  
  END DO
  
  CALL MPI_FINALIZE(IERROR)
  
  END PROGRAM
  </code></pre>