我正在使用MPI_Reduce和MPI_Scatter函数在“N”个处理器中分散整数数组并打印部分和累积数组的总和。我在visual studio 2010上使用Microsoft MPI(MSMPI)。但是每次执行时都会在标题“Debug Assertion Failed”下给出一个异常“_CrtlsValidHeapPointer(PuserData)”代码如下
enter code here
#include <mpi.h>
#include<iostream>
using namespace std;
int main(int argc, char *argv[]) {
int size;
int rank;
int partialsum=0;
int root =0;
int accum=0;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int *globaldata = NULL;
int *localdata = new int(4);
if (rank == root) {
globaldata = new int(size*4);
for (int i=0; i<(size*4); i++)
globaldata[i] = 2*i+1;
cout<<"Processor"<<rank<<" has global data: ";
for (int i=0; i<(size*4); i++)
cout<<globaldata[i]<<" ";
cout<<"\n";
}
MPI_Scatter(globaldata, 4, MPI_INT, localdata, 4, MPI_INT, root, MPI_COMM_WORLD);
cout<<"Processor "<<rank<<"has local data";
for(int i=0; i<4;i++)
cout<<" "<<localdata[i];
cout<<endl;
for(int k=0;k<4;k++)
partialsum += localdata[k];
cout<<"Processor "<<rank<<" Partial Sum = "<<partialsum<<"\n";
MPI_Reduce(&partialsum,&accum,1,MPI_INT,MPI_SUM, root,MPI_COMM_WORLD);
if (rank == 0) {
cout<<"Processor "<<rank<<" Accumulated Sum = "<<accum;
}
MPI_Finalize();
return 0;
}
答案 0 :(得分:0)
错误很简单,就在这里:
globaldata = new int(size*4);
使用new
运算符分配动态数组的语法是new type[size]
:
globaldata = new int[size*4];
在您的情况下,分配单个int
的空间并将其设置为size*4
,并且紧跟在根分配内存之后的初始化代码将覆盖已分配内存的末尾,从而破坏堆结构。