3 ms·
> memcpy actually has a few semantics that cannot be legally expressed in C (specifically, strict aliasing doesn't kick in). Are you sure? I hear this a lot, b
by rossy 6y ago
> memcpy actually has a few semantics that cannot be legally expressed in C (specifically, strict aliasing doesn't kick in).
Are you sure? I hear this a lot, but I don't think it's really true. char pointers are allowed to alias pointers to any other type in standard C (C17 6.5p7,) so unless I'm missing something, a correct C implementation of memcpy could just cast both its arguments to char pointers and copy them char-by-char.
I agree with your premise that the call to memcpy() is undefined, but I think that's entirely because of the conflicting definition, and has nothing to do with any special semantics of memcpy, so it would equally apply to any other standard library function.
- jcranmer 6y ago> Are you sure? I hear this a lot, but I don't think it's really true. char pointers are allowed to alias pointers to any other type in standard C (C17 6.5p7,) so unless I'm missing something, a correct C implementation of memcpy could just cast both its arguments to char pointers and copy them char-by-char. I'm not completely certain. I have definitely seen this assertion before made by people more well-versed in the C standard than I, but I don't recall the exact argument. I think it may be the case that the write-via-char causes the effective type of memory to change (so it can only be read by char from that point on), but again, I don't trust my judgement here.
- rossy 6y agoI think it might be an out-of-date assertion, but I'm not sure either since I also hear it from people who seem to be well-versed in the C standard. The only place in C17 where I can see memcpy singled out (6.5p6) also mentions copying "as an array of character type." The definition of memcpy itself just describes it as copying characters. It's true that some types can have bit patterns that are "trap representations," that is, they cause undefined behaviour when used, but memcpy can also create trap representations. You could memcpy to copy the bit pattern of a signalling NaN from an int into a float, for example. memmove on the other hand can't be implemented in standard C, but it can be implemented on most platforms using only implementation-defined behaviour, because casting a pointer to an intptr_t is implementation-defined, but on most platforms with a flat memory model, it gives you the linear memory address.