Rychu
Rychu

Reputation: 1020

Memcpy crash depending on pointer type

I'm using this helper function to pack different data types into a single buffer:

template <class T>
static inline void PushBack(T& value, void*& buffer) {
    T* typedBuffer = (T*)buffer;
    memcpy(buffer, &value, sizeof(value));
    typedBuffer++;
    buffer = typedBuffer;
}

I'm calling in a loop with 12B and 16B vectors (3 or 4 floats), and it works fine.

However, my other approaches doesn't:

template <class T>
static inline void PushBack(T& value, void*& buffer) {
    T* typedBuffer = (T*)buffer;
    memcpy((T*)buffer, &value, sizeof(value)); //crash on 16B
    typedBuffer++;
    buffer = typedBuffer;
}

template <class T>
static inline void PushBack(T& value, void*& buffer) {
    T* typedBuffer = (T*)buffer;
    memcpy(typedBuffer, &value, sizeof(value)); //crash
    typedBuffer++;
    buffer = typedBuffer;
}

template <class T>
static inline void PushBack(T& value, void*& buffer) {
    T* typedBuffer = (T*)buffer;
    *typedBuffer = value; //crash
    typedBuffer++;
    buffer = typedBuffer;
}

Those three examples always crash while copying 16B value, after previously copying total amount of 36B with EXC_BAD_ACCESS (EXC_I386_GPFLT).

This was run on intel and was compiled as release (fastest, smallest). I wasn't able to check what's happening in the assembly yet.

When I copy only 16B vectors, the problem doesn't occur, so I assume this is related to fact that pointer is not aligned to 16B. I could understand it in the last case (copy via pointer to pointer), but why does it matter in memcpy?

Upvotes: 1

Views: 911

Answers (1)

Rychu
Rychu

Reputation: 1020

Solved - in one case struct from external library was forcing the alignment.

Upvotes: 1

Related Questions