'How to use MPI_BCast with dynamic array of own datatype objects

There was a problem with passing dynamic array of object pointers via MPI_BCast(...). When I try to send array that I got error ended prematurely and may have crashed. exit code 0xc0000005. If I use MPI_BCast(...) with one object (like this MPI_Bcast(myObjArray[0], dataTypeMyObject, 1, 0, MPI_COMM_WORLD);) it work correctly. What I need to change in my implementation to send the whole array? Here is the code of my classes

class Vector3 final
{
public:
    double x;
    double y;
    double z;
//...(methods)
}
class MyObject final
{
public:
    Vector3 Force;
    Vector3 Speed;
//...(methods)
};

Here is a code of datatype init

MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Datatype dataTypeVec3;
int          lenVec3[3] = { 1, 1, 1 };
MPI_Aint     posVec3[3] = { offsetof(class Vector3, x),offsetof(class Vector3, y), offsetof(class Vector3, z) };
MPI_Datatype typVec3[3] = { MPI_DOUBLE,MPI_DOUBLE,MPI_DOUBLE };
MPI_Type_create_struct(3, lenVec3, posVec3, typVec3, &dataTypeVec3);
MPI_Type_commit(&dataTypeVec3);
MPI_Datatype dataTypeMyObject;
int          lenMyObject[2] = { 1, 1 };
MPI_Aint     posMyObject[2] = { offsetof(class MyObject, Force),offsetof(class MyObject, Speed)};
MPI_Datatype typMyObject[2] = { dataTypeVec3, dataTypeVec3};
MPI_Type_create_struct(2, lenMyObject, posMyObject, typMyObject, &dataTypeMyObject);
MPI_Type_commit(&dataTypeMyObject);

Here is a part of the code with MPI_BCast(...)

MyObject** myObjArray = new MyObject * [10];
for (int i = 0; i < 10; ++i)
{
    myobjArray[i] = new MyObject();
}
if(rank == 0)
   myObjArray[0]->Speed = {5, 0, 0};
MPI_Bcast(myObjArray, 10, dataTypeMyObject, 0, MPI_COMM_WORLD); // Problem is here
if(rank != 0)
   std::cout << "rank = "<< rank << " and speed.x = " << myObjArray[0].Speed.x << std::endl;


Solution 1:[1]

MPI_Bcast() expects that the input elements are continuous in memory, i.e. that the 10 MyObject instances are located "behind each other" in memory. But in your case you pass in an array of pointers into MPI_Bcast(), but MPI_Bcast() will not dereference the individual pointers. Instead, try

MyObject * myObjArray = new MyObject[10];
// ... initialize objects on rank 0
MPI_Bcast(myObjArray, 10, dataTypeMyObject, 0, MPI_COMM_WORLD);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sedenion