I have the following test program:
#include <string.h>
int q(int *p) {
int x;
memcpy(&x,p,sizeof(int));
x+=12;
memcpy(p,&x,sizeof(int));
return p[0];
}
When I compile this using GCC 4.7.2 for arm-linux-gnueabihf, the compiler suspects that the pointer accesses may be unaligned, annotating the loads and stores in the assembly output, for example:
ldr r0, [r0, #0] @ unaligned
If I compile with -mno-unaligned-access
, the compiler does not emit direct loads and stores at all but calls the library memcpy
instead. But in fact, the pointers in this case should never be unaligned. Is this an overlook in gcc, or am I mistaken?
int q(int *restrict p) { p[0]+=12; return p[0];}
.mov r3,r0
,ldr r0,[r0]
,add r0,r0,#12
,str r0,[r3]
,blx
. Why do you want to code this? It is true that it should be aligned. As others have noted, you are confusing it withmemcpy()
. At the very least,x = p[0];
seems semi-sane. Why are you usingmemcpy()
as an assignment? The next person will come along and proclaim that*p
is a byte-swapped version. Maybe the larger problem will help? – artless noisememcpy
is to be compatible with strict-aliasing rules. The givenint *
pointer may be derived from a pointer to an another type. – Juho Östmangcc
is generatingmemcpy
, because ifint*p
is achar*p
in disguise then it may not be aligned at all. So I'm not even sure the compiler could decide at all (apart from whole program analysis), thatint*p
is aligned. And considering your motivationgcc
is right. – Bryan Olivierint*
, it is a promise to the compiler that the result is properly aligned. The compiler is not required to support unaligned access throughint*
, gcc, for example, has packed structs for that. – Juho Östman