The following code defines a packed (alignment 1) structure where the dwBug
member is not aligned correctly. If such member is assigned to via means of a reference parameter, the assignemnt fails on architectures that do not support unaligned accesses such as ARM.
I am not 100% sure that what I am doing is legal; my understanding is however that unless I am explicitely casting the compiler should keep a track of whether it can copy data as is or it has to resolve the unaligned access. There are no warnings even with -Wall
#include <stdint.h>
#include <stdio.h>
#pragma pack(1)
typedef struct {
uint16_t w1;
uint32_t dwBug;
} STest;
#pragma pack()
class CTest
{
public:
void testIt()
{
copyUnaligned(member.dwBug);
printf("%08x\n", member.dwBug);
}
private:
void copyUnaligned(uint32_t ©It)
{
copyIt = 0x12345678;
}
STest member;
};
int main(int, char **)
{
CTest test;
test.testIt();
}
The output of this code is 00001234
# cat /proc/cpuinfo
model name : ARM926EJ-S rev 5 (v5l)
Features : swp half fastmult edsp java
CPU implementer : 0x41
CPU architecture: 5TEJ
CPU variant : 0x0
CPU part : 0x926
CPU revision : 5
gcc is a 5.3.1 cross-compiler built for a arm-linux-gnueabi
target.
Thanks