【发布时间】:2014-07-03 11:49:20
【问题描述】:
我在发送从指向结构的指针构建的 zmq 消息时遇到问题,该结构包含其他结构。
服务器代码:
#include <zmq.hpp>
#include <string>
#include <iostream>
using namespace zmq;
using namespace std;
struct structB{
int a;
string c;
};
struct structC{
int z;
struct structB b;
};
int main()
{
context_t context(1);
socket_t *socket = new socket_t(context,ZMQ_REP);
socket->bind("tcp://*:5555");
message_t *request = new message_t();
socket->recv(request);
struct structB messageB;
messageB.a=0;
messageB.c="aa";
struct structC *messageC = new struct structC;
messageC->z = 4;
messageC->b = messageB;
char *buffer = (char*)(messageC);
message_t *reply = new message_t((void*)buffer,
+sizeof(struct structB)
+sizeof(struct structC)
,0);
socket->send(*reply);
return 0;
}
客户端代码:
#include <zmq.hpp>
#include <iostream>
#include <string>
using namespace std;
using namespace zmq;
struct structB{
int a;
string c;
};
struct structC{
int z;
struct structB b;
};
int main()
{
context_t context(1);
socket_t *socket = new socket_t(context,ZMQ_REQ);
socket->connect("tcp://*:5555");
const char* buffer = "abc";
message_t *request = new message_t((void*)buffer,sizeof(char*),0);
socket->send(*request);
message_t *reply = new message_t;
socket->recv(reply);
struct structC *messageC = new struct structC;
messageC = static_cast<struct structC*>(reply->data());
cout<<messageC->b.a<<endl;//no crash here
struct structB messageB = messageC->b;//Segmentation fault (core dumped)
return 0;
}
当我尝试使用 structB 中名为“c”的字符串时,该程序崩溃。如果我尝试打印它,或者像上面的例子那样分配整个 structB 都没关系。
问题出在哪里?我应该以不同的方式在服务器端创建 message_t *reply 吗?
【问题讨论】:
-
你奇怪地混合了 C 和 C++ 语法(在 C 中,结构是单独的命名空间,并且在使用时需要
struct关键字,但在 C++ 中却不需要。为什么有时 使用它?)以及堆栈和堆分配对象的类似奇怪组合(为什么你在堆栈上创建messageB而在堆上创建messageC?messageC也可以在堆栈上创建。messageB是messageC的一部分;您不需要单独的实例。)