memcpy / Language Lawyer / optimization question

Steve Ellcey sje@cup.hp.com
Thu Dec 9 19:33:00 GMT 2004


I have a question about memcpy and when it is legal to turn it into a
simple assignment.  The first memcpy in the program below will cause an
abort on IA64 when compiled with -O2 because it gets turned into integer
assignment and p is not properly aligned.  I think this is OK.  The last
memcpy, where I put in a cast to (char *), will not assume any alignment
and this compiles and runs correctly on IA64 with -O2.  Again, I think
this is OK.

My question is about the second memcpy where I cast to (void *).  This
still results in an abort on IA64 because it is still assuming integer
alignment (and thus changing the code to do an integer assignment).  Is
it legal to do this transformation with the (void *) cast?

I ran into this in the libgfortran where I am trying to replace an
assignment of a long into a (possibly) unaligned buffer with a call to
memcpy.

Steve Ellcey
sje@cup.hp.com


------------------------------

#include <string.h>

static char buffer[80];
static int *foo();

main ()
{
        int i;
        int *p;

        i = 0;
        p = foo();

/* Causes core dump with -O2 */
        memcpy(p, &i, sizeof (int));
/* Causes core dump with -O2 */
        memcpy((void *) p, (void *) &i, sizeof (int));
/* Works with -O2 */
        memcpy((char *) p, (char *) &i, sizeof (int));
}

int *foo()
{
        return (int *) &buffer[1];
}



More information about the Gcc mailing list