我不太明白为什么我不能广播存储在堆中的数组(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)
最佳答案
简而言之,您应该将 &A
替换为 A
。
这个案例中到底发生了什么?内存损坏。
double *A
驻留在堆栈上(A 位于堆中)。
MPI_Bcast(&A, n,,,)
将修改指针本身,并且堆栈上的更多数据 int proc
和 int 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
关于c++ - MPI_广播: Stack vs Heap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27975902/