问题
Possible Duplicate:
memcpy vs memmove
Does memmove actually "move" a chunk of memory? If so, does it leave the memory with zeros? Or, is it just like memcpy? I am looking at the man page, and I do not believe my assumption is correct. If I want to move a chunk of memory using memmove, would I have to manually zero out the chunk of memory where I did the move?
回答1:
memmove
has nothing to do with clearing the old memory, and in fact in the only situations where you would want to use memmove
, clearing the old memory would destroy the data you just copied! That's because memmove
is only useful when you expect the source and destination ranges to overlap.
Usually, if you find yourself needing memmove
, it's indicative that you have a major fundamental inefficiency in your design. For instance, often new C programmers will try to use memmove
to remove the first few characters of a string (e.g. memmove(s, &s[1], len)
) rather than just using s+1
or &s[1]
to address the tail of the string. Algorithms containing memmove
rarely perform better than O(n^2).
回答2:
Not quite:
The main difference between memmove
and memcpy
is that memmove
can be used to relocate a piece of memory to somewhere that overlaps the memory block that you're trying to move. And therefore the original pointer will no longer be valid.
With memcpy
, on the other hand, the two areas cannot overlap.
memmove
doesn't zero the original memory block though. If you want to do that, you'll have to explicitly do it yourself with memset. As a rule, C routines don't waste cycles doing things that may not be necessary, such as zeroing memory. Compare with malloc
, which likewise does not zero the memory block.
来源:https://stackoverflow.com/questions/5877173/does-memmove-actually-move-a-chunk-of-memory-and-leave-behind-zeros-at-the-sou