我有以下一系列事件:
for(int i = 0; i < 4; i++)
{
int seqNum;
int ackNum;
int pldSize;
char* payload = (char*)malloc(DEFINED_SIZE);
//buffer updated each loop, assume: 140hello!
Packet::decap(buffer, seqNum, ackNum, pldSize, payload);
Packet p = Packet(seqNum, ackNum, pldSize, payload);
dataMap.insert(pair<int,struct Packet>(seqNum, p));
}
...
struct Packet
{
Packet(int,int,int,char*);
int seqNum;
int ackNum;
int payloadSize;
char* payload;
char* encap();
static void decap(char* datagram, int & seqn, int & ackn, int & bytes, char* pyld);
};
void
Packet::decap(char* datagram, int & seqn, int & ackn, int & bytes, char* pyld)
{
memcpy(&seqn, datagram, sizeof(int));
memcpy(&ackn, &datagram[4], sizeof(int));
memcpy(&bytes, &datagram[8], sizeof(int));
memcpy(pyld, &datagram[12], bytes);
}
Packet::Packet(int seq, int ack, int sz, char* pld)
{
seqNum = seq;
ackNum = ack;
payloadSize = sz;
memcpy(pld, &payload, sz);
}
...
map<int, struct Packet>::iterator dataIter = dataMap.begin();
while(dataIter != dataMap.end())
{
outfile.write(dataIter->second.payload, dataIter->second.payloadSize); //<<< Crash
dataIter++;
}
我无法弄清楚我在哪一点上复制/破坏了我的payload
记忆..有没有人看到我遗失的任何东西?
答案 0 :(得分:0)
这一行似乎是罪魁祸首,
memcpy(pyld, &datagram[12], bytes);
在此行之前打印bytes
的值。
答案 1 :(得分:0)
使用自动内存管理的C ++ 11示例:
typedef std::array<char, DEFINED_SIZE> packet_t;
typedef std::shared_ptr<packet_t> shared_packet_t;
for(int i = 0; i < 4; i++)
{
int seqNum;
int ackNum;
int pldSize;
// memory allocated here as new packet_t() but owned by shared_packet_t
shared_packet_t payload(new packet_t());
//buffer updated each loop, assume: 140hello!
Packet::decap(buffer, seqNum, ackNum, pldSize, payload);
// a second reference to packet_t exists in p
Packet p(seqNum, ackNum, pldSize, payload);
// a third reference to packet_t exists in a new copy of p that was created
// when pair<> was constructed
dataMap.insert(pair<int,struct Packet>(seqNum, p));
// payload and p are auto released here, but a reference to packet_t
// still exists via the reference to Packet in pair<> in the dataMap
}
struct Packet
{
Packet(int,int,int,shared_packet_t);
int seqNum;
int ackNum;
int payloadSize;
shared_packet_t payload;
char* encap();
static void decap(char* datagram, int & seqn, int & ackn, int & bytes, shared_packet_t pyld);
};
void
Packet::decap(char* datagram, int & seqn, int & ackn, int & bytes, shared_packet_t pyld)
{
memcpy(&seqn, datagram, sizeof(int));
memcpy(&ackn, &datagram[4], sizeof(int));
memcpy(&bytes, &datagram[8], sizeof(int));
memcpy(pyld->data(), &datagram[12], bytes);
}
Packet::Packet(int seq, int ack, int sz, shared_packet_t pld)
:seqNum(seq), ackNum(ack), payloadSize(sz), payload(pld)
{
}
...
map<int, struct Packet>::iterator dataIter = dataMap.begin();
while(dataIter != dataMap.end())
{
outfile.write(dataIter->second.payload->data(), dataIter->second.payloadSize);
dataIter++;
}
应该用c ++ -std = c ++ 11
编译答案 2 :(得分:-1)
memcpy(pld, &payload, sz);
我怀疑你想要这个...
payload = pld