Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which one to use - memmove() or memcpy() - when buffers don't overlap?

Tags:

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?

like image 678
sharptooth Avatar asked Dec 25 '09 11:12

sharptooth


People also ask

Can memcpy overlap?

The CRT function memcpy doesn't support overlapping memory.

Is Memmove faster than memcpy?

memcpy is still a little bit slower than memmove.

How memcpy () and Memmove () do compare in terms of performance?

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.

What is the difference between the Memmove () and memcpy () function?

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.


1 Answers

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.

like image 151
Stephen Canon Avatar answered Sep 20 '22 17:09

Stephen Canon