I have a strange situation where using std::copy is causing a seg fault where as using memcpy appears to work correctly.
I am creating a PacketHeader object inside a Google Test function.
I have confirmed that the data going into the object is valid so I’m probably being stupid and have missed something obvious with the std::copy syntax.
GCC version : 4.4.6 20120305 (Red Hat 4.4.6-4)
GTest version : 1.6.0
Also linking with boost::options and libpcap
TEST(SetIP, GoodVals)
{
char errbuf[PCAP_ERRBUF_SIZE];
pcap_t * handle = pcap_open_offline("./test_files/PCAP_Good.pcap", errbuf);
pcap_pkthdr * header;
const unsigned char * pkt_data;
//Load one packet from the PCAP, doesn't matter what
pcap_next_ex(handle, &header, &pkt_data);
PacketHeader p(header);
}
PacketHeader::PacketHeader(const struct pcap_pkthdr * aPacketHeader) : prPacketHeader(NULL)
{
prPacketHeader = new struct pcap_pkthdr;
//This doesn't work
//std::copy(aPacketHeader, aPacketHeader + sizeof(struct pcap_pkthdr), prPacketHeader);
//This works
memcpy(prPacketHeader, aPacketHeader, sizeof(struct pcap_pkthdr));
}
The expression
doesn’t do what you expect it to. It actually adds
sizeof(pcap_pkthdr) * sizeof(pcap_pkthdr)to the pointer base address.Remember that
aPointer + somethingis the same asaPointer[something].Either add only
1:or typecast to
char*:The obvious solution should of course to use simple struct-to-struct copying: