I have a problem sending zmq message built from the pointer to struct, which contains other struct.
The server code:
#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; } Client code:
#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; } This program crashes when I try to use string called "c" from structB. It doesn't matter if I try to print it, or assign whole structB as in above example.
Where is the problem? Should I create message_t *reply on server side in different way?
structkeyword when used, but in C++ they don't. Why do you sometimes use it?) and similarly strange mix of stack and heap allocated objects (Why do you createmessageBon stack andmessageCon heap?messageCcan also be created on stack. AndmessageBis part ofmessageC; you don't need a separate instance.)