creekorful
creekorful

Reputation: 362

EXC_BAD_ACCESS while copying memory to structure

I have face a strange EXC_BAD_ACCESS while trying to use std::memcpy to copy bunch of bytes.

I have an std::string containing the data from a PNG file. I use the following structure to represent PNG Chunk:

struct PngChunk
{
    int length;
    char type[4]; // IHDR, PLTE, IDAT, IEND, ...
    unsigned char* data;
    unsigned int crc;

} typedef PngChunk;

And I'm reading it chunk by chunk in the following way:

First I read the length and the type:

std::memcpy((void*) &chunk, ptr, sizeof(unsigned int) + (sizeof(char) * 4));
ptr += sizeof(unsigned int) + (sizeof(char) * 4); // advance pointer to data

I swap the read length byte to little endian (needed because stored in big-endian). Then I read the chunk data like this:

chunk.data = new unsigned char[chunk.length];
std::memcpy((void*) &chunk.data, ptr, chunk.length);
ptr += chunk.length; // advance pointer to CRC

And finally I read the chunk CRC

std::memcpy((void*) &chunk.crc, ptr, sizeof(unsigned int));
ptr += sizeof(unsigned int);

When I output the chunk type/length I can clearly see that they are correctly read but when I try to access the data I face the above error. I have no idea why since the buffer I large enough to store the chunk data.

Does someone have an idea?

Thank in advance

Upvotes: 0

Views: 120

Answers (1)

Vennor
Vennor

Reputation: 656

I believe the problem originates from the fact that you're taking the address of data variable in the following line of code.

std::memcpy((void*) &chunk.data, ptr, chunk.length);

Since what you need is the address the variable points to, you have to drop the & before chunk.data.

Upvotes: 2

Related Questions