0

I'm using MPI_Gatherv to gather the data from every rank and for the gathered data, I want to store in a 2D array.

Here is part of my code:

       std::vector<int> n_of_BP;
    if(rank == 0)
    {
        n_of_BP.resize(size);
    }

    int n_of_BP_local = 100;
    MPI_Gather(&n_of_BP_local, 1, MPI_INT, &(n_of_BP[0]), 1, MPI_INT, 0, MPI_COMM_WORLD);
    std::vector<int> offsets;
    if(rank == 0)
    {
        offsets.resize(size);
        offsets[0] = 0;
        for(int i=1; i<size; i++)
        {
            offsets[i] = offsets[i-1] + 100;
        }
    }

    int sendBuf[100];

    for(int i=0; i<100; i++)
    {
        sendBuf[i] = i*rank;
    }
    int ** recvBuf;
    recvBuf = (int **) malloc(sizeof(int *)*size);
    for(int i=0; i<size; i++)
    {
        recvBuf[i] = (int *) malloc(sizeof(int)*100);
    }
    MPI_Gatherv(&(sendBuf[0]), n_of_BP_local, MPI_INT, &(recvBuf[0][0]), &(n_of_BP[0]), &(offsets[0]), MPI_INT, 0, MPI_COMM_WORLD);

The error occurs at the 'recvBuf' declaration and always gives memory corruption. When I declare 'recvBuf' as 'int recvBuf[size][100]', the code can wrong without error. But I want to use dynamic allocated array to declare the 'recvBuf', any suggestions about it? Thank you at first!

  • 1
    `recvBuf` should be allocated in consecutive memory (read **no** jagged array). There are plenty similar questions that were already answered on SO. – Gilles Gouaillardet May 29 '19 at 02:36
  • 1
    What does "the code can wrong without error" mean? I think you should rewrite a clearer sentence. – Linh Dao May 29 '19 at 02:45
  • 1
    What you allocate is, as mentioned, what is called a [*jagged array*](https://en.wikipedia.org/wiki/Jagged_array). What you create is more like an array of pointers instead of an array of arrays. And an array of pointers is [*very* different](https://stackoverflow.com/questions/18440205/casting-void-to-2d-array-of-int-c/18440456#18440456) from an array of arrays. – Some programmer dude May 29 '19 at 02:49

0 Answers0