TomP89
TomP89

Reputation: 1460

Segmentation fault with std::copy, memcpy works

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));

}

Upvotes: 2

Views: 1997

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409146

The expression

aPacketHeader + sizeof(struct pcap_pkthdr)

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 + something is the same as aPointer[something].

Either add only 1:

aPacketHeader + 1

or typecast to char*:

reinterpret_cast<char*>(aPacketHeader) + sizeof(struct pcap_pkthdr)

The obvious solution should of course to use simple struct-to-struct copying:

*prPacketHeader = *aPacketHeader;

Upvotes: 10

Related Questions