What is the difference between memmove and memcpy?

What is the difference between memmove and memcpy ? Which one do you usually use and how?


With memcpy , the destination cannot overlap the source at all. With memmove it can. This means that memmove might be very slightly slower than memcpy , as it cannot make the same assumptions.

For example, memcpy might always copy addresses from low to high. If the destination overlaps after the source, this means some addresses will be overwritten before copied. memmove would detect this and copy in the other direction - from high to low - in this case. However, checking this and switching to another (possibly less efficient) algorithm takes time.


memmove can handle overlapping memory, memcpy can't.

Consider

char[] str = "foo-bar";
memcpy(&str[3],&str[4],4); //might blow up

Obviously the source and destination now overlap, we're overwriting "-bar" with "bar". It's undefined behavior using memcpy if the source and destination overlap so in this case cases we need memmove .

memmove(&str[3],&str[4],4); //fine

From the memcpy man page.

The memcpy() function copies n bytes from memory area src to memory area dest. The memory areas should not overlap. Use memmove(3) if the memory areas do overlap.

链接地址: http://www.djcxy.com/p/89576.html

上一篇: memcpy()vs memmove()

下一篇: memmove和memcpy有什么区别?