| ||||||||
Technical Support Support Resources Product Information | ARM: UN-ALIGN ACCESS GIVES UNEXPECTED RESULTSInformation in this article applies to:
QUESTIONI am testing un-aligned memory accesses using the RealView MDK-ARM. A simplified example is shown below:
#pragma pack(1)
unsigned char buf[40];
int main (void) {
*((short *)&buf[0]) = 0x77ff;
*((int *)&buf[2]) = 0x12345678;
printf("%x %x %x %x \n", buf[0], buf[1], buf[2], buf[3]);
}
I expect that the output is FF 77 34 12 since I am running the code on a little endian microcontroller. However, it appears that the value 0x12345678 is written to buf[0] since I get the following output: 78 56 34 12 What is wrong here? ANSWERBy default, ARM7 and ARM9 based microcontrollers do not allow un-aligned accesses to 16-bit and 32-bit data types. Cortex-M3 supports even un-aligned accesses, so the program above would behave correctly. Depending on the device implementation, unaligned accesses may either result in a DATA ABORT or swapped memory bytes (the strange output you have seen). This behavior is described in the Architecture Reference Manuals of the CPU core which are available on www.arm.com. You can solve the problem by using the __packed which instructs the Compiler to use byte accesses instead of word or half-word accesses. Therefore the following code will generate the expected results:
unsigned char buf[40];
int main (void) {
*((__packed short *)&buf[0]) = 0x77ff;
*((__packed int *)&buf[2]) = 0x12345678;
printf("%x %x %x %x \n", buf[0], buf[1], buf[2], buf[3]);
}
MORE INFORMATION
FORUM THREADSThe following Discussion Forum threads may provide information related to this topic. Last Reviewed: Tuesday, January 09, 2007 | |||||||
| ||||||||