c++ - MPI_广播: Stack vs Heap

标签 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)

最佳答案

简而言之,您应该将 &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

关于c++ - MPI_广播: Stack vs Heap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27975902/

相关文章:

c++ - boost 日期之前缺少模板参数

c++ - 如何将数字列表从字符串复制到 C++ vector

c++ - 如何使用 MPI 库为进程子集调用 (c++) 函数?

c++ - 来自 QWidget 的 QMainWindow 的 setWindowState

c++ - while 循环因 eof 检查停止得太晚

c++ - C语言有前置自增和后置自增的历史原因是什么?

c - 使用 MPI 在后台收听和回复

c - C 中的 MPI_Scatter 结构

c - 使用 CUDA + MPI 的矩阵乘法

c - MPI 和 C 结构