Using memcpy()
when source and destination overlap can lead to undefined behaviour - in those cases only memmove()
can be used.
But what if I know for sure buffers don't overlap - is there a reason to use specifically memcpy()
or specifically memmove()
? Which should I use and why?
The CRT function memcpy doesn't support overlapping memory.
memcpy is still a little bit slower than memmove.
It depends on the target machine and the implementation. Copy data is slow. Copy data twice will be slower. That memmove might be slower than memcpy is because it is able to handle overlapping memory, but memmove still only copies the data once.
Answer: memcpy() function is is used to copy a specified number of bytes from one memory to another. memmove() function is used to copy a specified number of bytes from one memory to another or to overlap on same memory.
Assuming a sane library implementor, memcpy
will always be at least as fast as memmove
. However, on most platforms the difference will be minimal, and on many platforms memcpy
is just an alias for memmove
to support legacy code that (incorrectly) calls memcpy
on overlapping buffers.
Both memcpy
and memmove
should be written to take advantage of the fastest loads and stores available on the platform.
To answer your question: you should use the one that is semantically correct. If you can guarantee that the buffers do not overlap, you should use memcpy
. If you cannot guarantee that the buffers don't overlap, you should use memmove
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With