ARM Technical Support Knowledge Articles

UN-ALIGN ACCESS GIVES UNEXPECTED RESULTS

Applies to: ARM Development Tools

Answer


Information in this article applies to:


QUESTION

I 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 
", 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?

ANSWER

By 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 
", buf[0], buf[1], buf[2], buf[3]);
}

MORE INFORMATION

Article last edited on: 2007-01-09 14:46:26

Rate this article

[Bad]
|
|
[Good]
Disagree? Move your mouse over the bar and click

Did you find this article helpful? Yes No

How can we improve this article?

Link to this article
Copyright © 2011 ARM Limited. All rights reserved. External (Open), Non-Confidential