Compiler Memory Alignment Issue

Martin Guy
Fri Feb 3 09:52:00 GMT 2012

On 2 February 2012 19:15, Richard Koch <> wrote:
> know that ptr is declared as a pointer to an integer and interpret "*(ptr + 1)"
> as adding 4 BYTES to ptr.
>         unsigned char buffer[8], i;
>         int *ptr = (int *) buffer;
>         printf("size of int is: %d\n", sizeof(int));
>         memset(buffer, 0xff, sizeof buffer);
>         *(ptr + 1) = 0x1234;
>         for (i=0; i<(sizeof(buffer) +1); i++)
>                 printf("buffer[%d]=%x\n", i, buffer[i]);
> }
> RESULTS WITH crosstool-linux-gnueabi-2005q3-2:
> size of int is: 4
> buffer[0]=ff
> buffer[1]=ff
> buffer[2]=ff
> buffer[3]=ff
> buffer[4]=34
> buffer[5]=12
> buffer[6]=0
> buffer[7]=0
> buffer[8]=0
> RESULTS WITH crosstools-ng:
> size of int is: 4
> buffer[0]=ff
> buffer[1]=34
> buffer[2]=12
> buffer[3]=0
> buffer[4]=0
> buffer[5]=ff
> buffer[6]=ff
> buffer[7]=ff
> buffer[8]=8

I can reproduce your first result with gcc.4,4 and your second result
with gcc-4.3 (plain native debian compilers), which corresponds to the
gcc version you are using in crosstool.

The problem is that your char buffer is not word-aligned, so you can't
poke ints into it with predictable results.  On ARM a nonaligned word
access writes into *(int*)(char *)ptr & ~3) and the value it writes is
byte-rotated in such a way as to write the least significant byte into
*(char *)ptr.
It looks like, in your failing case, that the bottom two bits of the
address of buffer[0] are 1 and 1.

The results also depend on the setting of /pro/cpu/alignment. The
default value of 0 gives the above behaviour,
  echo 4 > /proc/cpu/alignment
will cause a fatal signal on misaligned word accesses and
  echo 2 > /proc/cpu/alignment
will trap the misaligned access in the kernel and do what you are
expecting (i386- and vax-like behaviour).

A more robust solution would be to declare
char buffer[8] __attribute__ ((aligned (sizeof(int))));
int buffer[2];

A further test you can run to verify whether it is the compiler bug
you suspect or an alignment issue is to disassemble the object code
  arm-linux-gnueabi-objdump -d a.out | less
(or whatever your toolchain is called) to check whether it is adding
one or four to the pointer.


For unsubscribe information see

More information about the crossgcc mailing list