MPI_Bcast:Stack vs Heap

时间:2015-01-16 01:18:32

标签: c++ mpi

我不太明白为什么我不能广播存储在堆中的数组(new double [n]),但如果数组存储在堆栈中它运行正常。
请让我知道发生了什么。

#include "mpi.h"

int main(int argc, char* argv[])
{

    MPI_Init(&argc, &argv);
    int iproc;
    MPI_Comm_rank(MPI_COMM_WORLD, &iproc);

    int n = 1000;

    double *A=new double[n];
    //double A[n];                                                                                                       

    printf("Before Bcast from rank %d\n",iproc);
    MPI_Bcast(&A, n, MPI_DOUBLE, 0, MPI_COMM_WORLD);
    printf("After Bcast from rank %d\n",iproc);

    delete[] A;
    MPI_Finalize();
    return 0;
}

输出:

Before Bcast from rank 0
Before Bcast from rank 1
After Bcast from rank 0
After Bcast from rank 0  (why does this line show up again?)
APPLICATION TERMINATED WITH THE EXIT STRING: Hangup (signal 1)

1 个答案:

答案 0 :(得分:3)

简而言之,您应该将&A替换为A

在这种情况下发生了什么?内存损坏。

double *A驻留在堆栈上(A在堆中)。 MPI_Bcast(&A, n,,,)将修改指针本身,而堆栈int procint n上的更多数据是内存覆盖的牺牲品。

堆栈中的内存布局是

double* A;  // it points some new address
int n;      // next to *A
int iproc;  // next to n

它是16个字节(在x86_64环境中) MPI_Bcast(&A, n,,将从&A为40000字节写入0。其中包括&n&iproc

它提供A == n == iproc == 0

的结果

因此delete[] A;被强制删除NULL指针,导致段错误。

避免这些悲剧(在脚下射击)

const double *A = new double[n];

const 会救你。详情请参阅http://www.codeguru.com/cpp/cpp/cpp_mfc/general/article.php/c6967/Constant-Pointers-and-Pointers-to-Constants.htm

相关问题