Compiler Memory Alignment Issue
Fri Feb 3 09:52:00 GMT 2012
On 2 February 2012 19:15, Richard Koch <firstname.lastname@example.org> 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, 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
> RESULTS WITH crosstools-ng:
> size of int is: 4
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
It looks like, in your failing case, that the bottom two bits of the
address of buffer 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 __attribute__ ((aligned (sizeof(int))));
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 http://sourceware.org/lists.html#faq
More information about the crossgcc