替换std :: map值时崩溃

时间:2018-05-07 09:16:22

标签: c++ sockets c++11 struct stdmap

我有这张地图

std::map<IPv4Address,std::vector<Agent>> report;

将代理定义为以下

typedef struct
{
    IPv4Address Address;
    AgentType Type;
    std::map <IPv4Address, IPRoute> RoutingTable;
    MetricType metric;
    int UpdateReceived = 0;
}Agent;

我通过tcp sockets发送此代理结构并将值保存在报告中std::map

int receive = recv(as.socket, (void *) &agent, sizeof(agent),0);

路由表最初为空。当路由表大小变为&gt; = 1时,应用程序在添加到地图时崩溃,如下所示:

             mutex.lock();
             PrintInfo("Mutex locked");
             if(report.find(as.ip) != report.end())
             {
                 //f tells us if the agent was connected before to the router
                 bool f = false;
                 std::vector<Agent> tmpv =report[as.ip];
                 int tmp;

                 PrintInfo("Vector loop");
                 for(std::size_t i=0 ; i < tmpv.size() ; i++)
                 {
                     if(tmpv[i].Type == agent.Type)
                     {
                         f = true;
                         tmp = i;
                         break;
                     }
                 }

                 PrintInfo("Vector loop End");

                 if(f)
                 {
                     PrintInfo("Found -> Replacing");
  --> This line crashes  report[as.ip][tmp] = agent;
                 }
                 else
                 {
                     PrintInfo("Not Found -> Adding");
                     report[as.ip].push_back(agent);
                 }


                 PrintInfo("After add");
             }

1 个答案:

答案 0 :(得分:0)

使用boost库序列化结构后,一切正常。

以下是序列化的示例:

结构:

typedef struct
{
    template<class Archive>
    void serialize(Archive &ar,const unsigned int version)
    {
        ar & Address & Type & InterceptionDuration & RoutingTable & metric & UpdateReceived;
    }

    IPv4Address Address;
    AgentType Type;
    double InterceptionDuration;
    std::map <IPv4Address, IPRoute> RoutingTable;
    MetricType metric;
    int UpdateReceived = 0;
}Agent;

序列化:

std::string SerializeAgent(Agent a)
{
    std::ostringstream archive_stream;
    boost::archive::text_oarchive archive(archive_stream);
    archive << a;
    std::string s = archive_stream.str();
    return s;
}

反序列化:

Agent DeserializeAgent(std::string s)
{
        Agent a;
        std::string r(&s[0],s.size());
        std::istringstream archive_stream(r);
        boost::archive::text_iarchive archive(archive_stream);
        archive >> a;
        return a;
}

通过套接字发送:

std::string s = SerializeAgent(agent);
send(reporterSendingSocket,s.c_str(),s.size(),0);

通过套接字接收:

std::vector<char> response(REPORT_MAX_BUFFER_SIZE);

int receive = recv(as.socket, (void *) &response[0], response.size(),0);