MPI_Bast:堆栈与堆
MPI_Bcast: Stack vs Heap
我不太明白为什么我不能广播存储在堆中的数组(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 %dn",iproc);
MPI_Bcast(&A, n, MPI_DOUBLE, 0, MPI_COMM_WORLD);
printf("After Bcast from rank %dn",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。包括CCD_ 9和CCD_。
它用A == n == iproc == 0
提供结果
所以delete[] A;
被强制删除空指针,这会导致segfault。
为了避免这些悲剧(射中自己的脚(
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
相关文章:
- 算法问题:查找从堆栈中弹出的所有序列
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- 为什么调用堆栈数组会导致内存泄漏
- gdb错误:Backtrace已停止:上一帧与此帧相同(堆栈已损坏?)
- 在 leetcode 上提交解决方案时出现堆栈缓冲区溢出错误
- 我的 int main() 中出现堆栈溢出错误
- 堆栈和队列是否像C++中的数组一样传递?
- 拥有映射的现代方法,该映射可以指向或引用已在堆栈上分配的不同类型的数据
- 为什么 STL 容器适配器堆栈中的 top 返回常量引用?
- 从堆栈分配的原始指针构造智能指针
- 在函数范围内在堆栈上分配的数组在离开函数时是否总是被释放?
- 堆栈中大小变量输入错误 (C++)
- 堆栈问题(平衡表达式问题集)
- C++ 在堆栈中包含多态属性的类对象存储
- 用于解析 win64 堆栈跟踪的命令行客户端(可以访问符号服务器)
- 在 C++ 中使用链表进行堆栈
- 变量周围的堆栈'...'已损坏
- 在 gtest 中初始化堆栈上的引用变量的隔离错误
- C++线程的可用堆栈大小