zeromq with protobuf segmentation fault while parsing in c++

前提是你 提交于 2019-12-24 14:28:38

问题


I am using zeromq with protobuf to send/recieve messages but code was crashing on receiver end with Segmentation fault (core dumped) error while parsing the received data.

Scan is my message.

sender.cpp

Scan proto_ls_msg;
proto_ls_msg.set_angle_min(0.0);
proto_ls_msg.set_angle_max(180.5);
std::string ls_msg_str;
proto_ls_msg.SerializeToString(&ls_msg_str);
zmq::message_t request (ls_msg_str.size());
memcpy (request.data(), ls_msg_str.c_str(),ls_msg_str.size());
socket.send (request);

collector.cpp

zmq::message_t recieved;
socket.recv (&recieved);
//thanks to πάντα ῥεῖ
std::string ls_msg_str((char*)recieved.data(),recieved.size()); 
Scan *pb_laser_msg_rcv;
pb_laser_msg_rcv->ParseFromString(ls_msg_str); // <--  Segmentation fault here

I tried different way of converting zmq::message_t to std::string but still it gives segmentation fault.

Edit update:

//std::string ls_msg_str((char*)recieved); 
  std::string ls_msg_str((char*)recieved.data(),recieved.size());

thanks.


回答1:


IIRC you can't directly cast a zmq::message_t to a string. You should probably only use the data member to create the string. Also the recieved.data is not '\0' terminated, so you would also need to pass the size when you construct the ls_msg_str instance:

std::string ls_msg_str((char*)recieved.data,recieved.size);
                                    // ^^^^          ^^^^


来源:https://stackoverflow.com/questions/24455770/zeromq-with-protobuf-segmentation-fault-while-parsing-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!