3 ms·
I think memcpy is fine because it operates on a special type that is allowed to alias anything. Strict aliasing has other fun issues like the impossibility of i
by anonymoushn 4y ago
I think memcpy is fine because it operates on a special type that is allowed to alias anything. Strict aliasing has other fun issues like the impossibility of implementing malloc-like functions or the lack of any requirement for access to non-char members of structs to work at all[0].
[0]: https://stackoverflow.com/questions/49298704/how-reason-about-strict-aliasing-for-malloc-like-functions#comment87025368_49988951 https://stackoverflow.com/questions/49298704/how-reason-abou...
- olliej 4y agomemcpy is UB because it reads padding bytes in structs. memmove fails as it requires pointer comparisons between separate allocations, which is UB.
- anonymoushn 4y agoSounds like we shouldn't use memcpy on structs containing padding!
- maccard 4y agoNo, memcpy is fine because it's a language level function. What you _can't_ do is implement your own memcpy alternative safely.
- nayuki 4y agomemcpy() and memmove() are language-level functions. They are allowed to do things that cannot be implemented in user code. The C standard library's implementation of these functions have tight integration with the compiler to ensure that it can implement all the required semantics without triggering undefined behavior.
- leni536 4y agoreading padding bytes is not UB. Comparing unrelated pointers is unspecified, not undefined. It's also an implementation detail of memmove. It can use a magical total order comparison of pointers that is otherwise unavailable to users of the language.