c++ - 段错误 : Struct Serialisation and MPI Data Transfer in C++

标签 c++ struct segmentation-fault mpi

我正在尝试将序列化结构从一个等级发送到另一个等级。结果是

Segmentation fault: 11

我不知道它来自哪里。

我试图通过打印出一些值来定位问题,并且代码总是在 MPI_SendMPI_Recv 之间中断,但由于它是段错误,因此无法确定这是问题的根源。请赐教。

int N = 11;
struct tests{
    int number;
    double *fx;
};

void locateMemoryTests(struct tests *t){
    t->fx = (double*) malloc(N*sizeof(double));
}

void he(struct tests *t, int N){
    int NRank, MyRank;
    MPI_Comm_rank( MPI_COMM_WORLD, &MyRank );
    MPI_Comm_size( MPI_COMM_WORLD, &NRank );
    int st = MyRank * int(N/2);
    int en = (MyRank+1) * int(N/2) + (N%2)*MyRank;

    for (int i=st; i<en; i++){
        t->fx[i] = i*i + 5*(i + t->number);
    }
    const int nitems        = 2;
    int blocklengths[2]     = {1, N};
    MPI_Datatype types[2]   = {MPI_INT, MPI_DOUBLE};
    MPI_Datatype mpi_tests_type;
    MPI_Aint offsets[2];

    offsets[0] = offsetof(tests, number);
    offsets[1] = offsetof(tests, fx);

    MPI_Type_create_struct(nitems, blocklengths, offsets, types, &mpi_tests_type);
    MPI_Type_commit(&mpi_tests_type);
    MPI_Comm_rank(MPI_COMM_WORLD, &MyRank);

    if (MyRank == 0){
        struct tests send;
        send.number = t->number;
        locateMemoryTests(&send);

        for (int i=0; i<N; i++){
            send.fx[i] = t->fx[i];
        }   

        MPI_Send(&send, 2, mpi_tests_type, 1, 111, MPI_COMM_WORLD);
        }
    else if (MyRank == 1){
        MPI_Status status;
        struct tests recv;
        locateMemoryTests(&recv);
        MPI_Recv(&recv, 2, mpi_tests_type, 0, 111, MPI_COMM_WORLD, &status);

    MPI_Type_free(&mpi_tests_type);
}


int main( int argc, char *argv[] ){
    int NRank, MyRank;
    MPI_Init( &argc, &argv );
    MPI_Comm_rank( MPI_COMM_WORLD, &MyRank );
    MPI_Comm_size( MPI_COMM_WORLD, &NRank );

    struct tests tt;
    tt.number = 5;
    locateMemoryTests(&tt);

    he(&tt,N);

    MPI_Finalize();
    return 0;
}

最佳答案

您的 MPI 派生数据类型描述了以下 C struct

struct tests{
    int number;
    double fx[N];
};

但是你用的是不同的

struct tests{
    int number;
    double *fx;
};

如果 N 不是常量,您可以声明

struct tests{
    int number;
    double fx[];
};

正确分配这样的结构取决于您。

另一种选择是保持相同的struct 定义,并手动MPI_Pack()MPI_Unpack() 将数据传入/传出临时缓冲区。

关于c++ - 段错误 : Struct Serialisation and MPI Data Transfer in C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56507811/

相关文章:

c++ - 如何将 Qline 坐标发送到 QPainter Widget

c++ - 将枚举(在结构内声明)值分配给结构内相同枚举类型的变量

C 结构 : what does this mean?

r - 在 Linux 中使用 mclapply 时 R 中出现奇怪的段错误

linux - 调用线程构造函数时出现段错误

c++ - 将类添加到基本 Qt GUI 应用程序时出现 Qt 链接器错误

c++ - 如何在 C++ 中使用单个 APDU 发送和获取数据?

c++ - 是否有一种工具可以帮助了解谁将特定参数传递给函数,以及该变量最初是在哪里创建的(在 C/C++ 中)

c - C中的结构误解

xcode - CGColorSpaceRef 不是 Swift 中的 AnyObject 吗?