This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: memcpy to an unaligned address
- From: Andrew Pinski <pinskia at physics dot uc dot edu>
- To: mrs at apple dot com (Mike Stump)
- Cc: dave dot korn at artimi dot com (Dave Korn), pkoning at equallogic dot com (Paul Koning), gcc at sources dot redhat dot com, sjackman at gmail dot com (Shaun Jackman)
- Date: Tue, 2 Aug 2005 16:37:53 -0400 (EDT)
- Subject: Re: memcpy to an unaligned address
>
> On Aug 2, 2005, at 1:15 PM, Shaun Jackman wrote:
> > There is no padding. The structure is defined as
> > __attribute__((packed)) to explicitly remove the padding. The result
> > is that gcc knows the unaligned four byte member is at an offset of
> > two bytes from the base of the struct, but uses a four byte load at
> > the unaligned address of base+2. I don't expect...
> > p->unaligned = n;
> > ... to work,
>
> Actually, that works just fine, with:
>
> typedef struct {
> unsigned short int a;
> unsigned int b;
> } __attribute__((packed)) st;
>
> void foo(st *s, int n)
> {
> s->b = n;
> }
>
> Ah, I was having trouble getting it to fail for me... Now I can:
>
> #include <memory.h>
>
> typedef struct {
> unsigned short int a;
> unsigned int b;
> } __attribute__((packed)) st;
>
> void foo(st *s, int n)
> {
> memcpy(&s->b, &n, sizeof n);
> }
>
> Yes, this is a compiler bug in the expansion of memcpy, please file a
> bug report. The solution is for the compiler to notice the memory
> alignment of the destination and `do-the-right-thing' when it isn't
> aligned.
No it is not, once you take the address (which should be rejected), it
is of type "unsigned int *" and not unaligned variable, passing it to
memcpy assumes the type alignment is the natural alignment.
-- Pinski