[英]C++ MPI code Seg Fault 11 when run
我正在尝试使用MPI创建一些服务器,并且可以将其编译,但是当我运行它时,它会立即出现段错误。 我试图添加打印语句以查看它崩溃的位置,但这无济于事。 我是使用MPI的新手,却找不到问题所在。 我使用的是Mac,并且试图找出llvm,因为我无法使用GDB来检查核心转储,因此,在此期间提供的任何帮助将不胜感激。
#include "mpi.h"
#include <iostream>
#include <list>
using namespace std;
void error(const char *msg)
{
perror(msg);
exit(1);
}
int main( int argc, char **argv )
{
int MAX_DATA = 255;
MPI_Comm client;
MPI_Status status;
char port_name[MPI_MAX_PORT_NAME];
int size, again;
double buf[MAX_DATA];
cout << "Did we get here? [1]";
MPI_Init(NULL, NULL);
MPI_Comm_size(MPI_COMM_WORLD, &size);
cout << "Did we get here before it pukes";
if (size != 1) error("ERROR");
// Create the random list
list<int> rand_list;
list<int>::iterator it;
for(int i = 0; i < 5; ++i)
{
int r;
r = rand();
rand_list.insert (it,r);
it++;
}
cout << "mylist contains:";
for (it=rand_list.begin(); it!=rand_list.end(); ++it)
{
cout << ' ' << *it;
cout << '\n';
}
MPI_Open_port(MPI_INFO_NULL, port_name);
printf("server available at %s\n",port_name);
while (1) {
MPI_Comm_accept( port_name, MPI_INFO_NULL, 0, MPI_COMM_WORLD, &client);
again = 1;
while (again) {
MPI_Recv( buf, MAX_DATA, MPI_DOUBLE,
MPI_ANY_SOURCE, MPI_ANY_TAG, client, &status );
switch (status.MPI_TAG) {
case 0: MPI_Comm_free( &client );
MPI_Close_port(port_name);
MPI_Finalize();
return 0;
case 1: MPI_Comm_disconnect( &client );
again = 0;
break;
case 2: /* do something */
cout << "Why did we get here?";
default:
/* Unexpected message type */
MPI_Abort( MPI_COMM_WORLD, 1 );
}
}
}
}
[asdfa:04443] *** Process received signal ***
[asdfa:04443] Signal: Segmentation fault: 11 (11)
[asdfa:04443] Signal code: Address not mapped (1)
[asdfa:04443] Failing at address: 0x0
[asdfa:04443] [ 0] 0 libsystem_platform.dylib 0x00007fff8ed1452a _sigtramp + 26
[asdfa:04443] [ 1] 0 ??? 0x0000000000000001 0x0 + 1
[asdfa:04443] [ 2] 0 server.o 0x000000010a40eba2 main + 834
[asdfa:04443] [ 3] 0 libdyld.dylib 0x00007fff9cb245ad start + 1
[asdfa:04443] *** End of error message ***
Segmentation fault: 11 (core dumped)
您的问题位于以下代码行:
list<int>::iterator it;
for(int i = 0; i < 5; ++i)
{
int r;
r = rand();
rand_list.insert (it,r);
it++;
}
有两个问题:
您声明了迭代器,但从未为其分配有效值,因此它指向任何地方。 但是,迭代器必须指向列表中的有效位置。 rand_list.begin()
和rand_list.end()
都是合法的,因此您需要:
list<int>::iterator it = rand_list.end();
然后,第一个参数是插入元素的位置。 新元素将插入在迭代器指向的位置之前 。 因此,无论您最初是选择begin()还是end()作为迭代器(无论如何,对于空列表而言,它们都是相同的),通过递增它,都可以将其递增到列表的末尾,这是未定义的行为。 只需始终在末尾插入即可:
rand_list.insert (rand_list.end(), r);
但是,为什么不简单地使用push_back
(或者,如果愿意,则使用push_front
)呢?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.