ytrembla
9/11/2008 9:57:00 AM
In article <6adede5b-beec-41f7-9218-cdfc623194f5@r66g2000hsg.googlegroups.com>,
<gw7rib@aol.com> wrote:
>On 10 Sep, 13:59, sam <sameer...@gmail.com> wrote:
>> (newbie)Technically what's the difference between memset() and
>> memcpy() functions?
>
>A more interesting question would be - what's the difference between
>memcpy() and memmove()?
>
>The answer to this one is that memcpy can go wrong if the place it's
>moving from and the place it's moving to overlap. As a simple example,
>suppose you ask it to copy 20 bytes from addresses [100-119] to
>addresses [105-124]. It might copy the contents of [100] to [105],
>then the contents of [101] to [106], etc, but when it gets to [105],
>instead of copying what was originally in [105], this has already been
>overwritten and so what it reads, and copies to [110], is what was
>originally in [100]. So instead of getting a copy of what was in
>[100-119], you get four copies of what was in [100-105].
>
>memmove() is guaranteed not to go wrong in this way.
Strictly speaking, memcpy did not go wrong. It did exactly what was
asked for which is copy byte by byte 20 bytes from address 100 to
address 105.
I would hesitate to recommend using memmove over memcpy in the general
case based on being resilient to this programming mistake because one
of the only justification to use memcpy is its efficiency. By virtue
of protecting against the above case, memmove has to be less efficient
than memcpy. Obviously, in 95% of cases you won't care about
efficiency so should use neither memcpy nor memmove but stick with
much safer things like copy constructors, assigment operator,
std::swap and std::copy.
Yannick