Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reinterpret_cast on unaligned memory

Tags:

c++

Assuming the following code:

struct A
{
    int a;
    int b;
};

char* buffer = receivedFromSomeWhere();

A a = *reinterpret_cast<A*>(buffer + 1);

If buffer + 0 is aligned on the size of an int, buffer + 1 will be most likely on an unaligned memory. The default copy constructor will probably happily copy the two unaligned int members a and b. On a x86/x64 architecture, except from slowing down the code, will it impact the copy construction of a in any nasty way?

I know that a good serialization would solve the unaligned memory problem (by maybe adding a padding somewhere in order that the A struct will be aligned in the buffer), but in my case i am not responsible for this part.

like image 832
Jiwan Avatar asked Aug 08 '13 14:08

Jiwan


1 Answers

The combination of C++ and using an x86_64 architecture is insufficient to guarantee that unaligned accesses are supported. You must have an additional guarantee from your specific C++ implementation that using the reinterpret_cast this way is supported, even if the address is unaligned. If you state your specific compiler and target system, somebody may be able to tell you whether it supports these operations.

In the absence of such a guarantee, you can use memcpy to copy bytes from an unaligned buffer into a POD (plain old data) object. A good compiler may optimize such accesses.

like image 95
Eric Postpischil Avatar answered Oct 18 '22 23:10

Eric Postpischil