我正在通过ZeroMQ连接发送一个结构。两个字段是正确的,但一个是损坏的。为了说明这个问题,我的代码尝试读取zmq消息的内容并创建一个新结构。
输出:
$ ./client
id = 100
successful = 1
data_size = 356515840
Segmentation fault
client.cc
#include <string>
#include <iostream>
#include "zmq.hpp"
#include "struct.h"
int main () {
zmq::context_t context (1);
zmq::socket_t socket (context, ZMQ_REQ);
socket.connect ("tcp://localhost:5555");
query q(100);
q.data_size = 3;
q.data = "abc";
q.successful = true;
zmq::message_t request = q.generate_message();
query test_query((char *) request.data());
return 0;
}
struct.h
#include <arpa/inet.h>
#include "zmq.hpp"
struct query {
long id;
bool successful;
long data_size;
std::string data;
query (long id) {
this->id = id;
this->successful = false;
this->data_size = 0;
this->data = "";
}
query (char *start) {
id = *((long*) start);
start += sizeof(long);
std::cout << "id = " << id << std::endl;
successful = *((bool*) start);
start += sizeof(bool);
std::cout << "successful = " << successful << std::endl;
data_size = *((long *) start);
data_size = ntohl(data_size);
start += sizeof(long);
std::cout << "data_size = " << data_size << std::endl;
data = std::string(start, data_size);
}
long get_total_size() {
return 2 * sizeof(long) + sizeof(bool) + data_size;
}
// The string is encoded by calling data.c_str()
zmq::message_t generate_message() {
long size = get_total_size();
zmq::message_t msg(size);
memcpy((void *) msg.data(), this, size);
char *loc_of_data = (char *) msg.data() + 2 * sizeof(long) + sizeof(bool);
memcpy((void *) loc_of_data, data.c_str(), data_size);
return msg;
}
};
答案 0 :(得分:2)
你忽略了填充。
因为您正在使用memcpy
,所以您在消息中使用与内存中结构中存在的布局相同的布局。并且结构中的long
,bool
,long
具有用于对齐目的的填充。
我建议您使用“普通旧数据”的子结构,并停止考虑2 * sizeof(long) + sizeof (bool)
。