memcpy() inlining and alignment

Martin v. Loewis martin@loewis.home.cs.tu-berlin.de
Fri Mar 3 17:47:00 GMT 2000


> foo(unsigned char *cp)
[...]
> 	src = (struct s *)(cp + 1);
[...]
> 	(1) Is this a compiler bug, or is the code making the memcpy()
> 	    call broken?

I just claimed in a previous message that the code is fine; rereading
the standard, I now think that it is neither-nor.

It is not the memcpy that would be incorrect - it is the assignment.
>From 6.3.2.3 (Pointers):

# A pointer to an object or incomplete type may be converted to a
# pointer to a different object or incomplete type. If the resulting
# pointer is not correctly aligned for the pointed-to type, the
# behavior is undefined. Otherwise, when converted back again, the
# result shall compare equal to the original pointer.

Since cp+1 is not correctly aligned 'struct s*', assigning it to src
results in undefined behaviour. That, of course, does include the
option of a later memcpy call crashing.

So far for the analysis of your code, what that means with respect to
gcc is more than I can analyse at the moment :-)

Good night,
Martin


More information about the Gcc-bugs mailing list