Reputation: 7434
I was reading from a c++ reference about memcpy
and memmove
and they seems to be doing the same thing except that memmove
has a specific think called (allowing the destination and source to overlap).
What is overlapping and when that happens?
Upvotes: 10
Views: 10978
Reputation: 17946
It's very simple. Consider memmove(dest, source, length)
.
If the range of bytes specified by the range source
to source + length - 1
include any bytes in the range specified by dest
to dest + length - 1
, the two ranges overlap.
This is most likely to happen when moving elements within an array. Example:
// Slide array down by one:
char array[N];
memmove( (void*) &array[0], (void*) &array[1], N - 1 );
That overlaps on elements 1 through N-2. Sliding the other direction has a similar overlap:
// Slide array up by one:
memmove( (void*) &array[1], (void*) &array[0], N - 1 );
If you were to attempt this same operation with memcpy()
, the resulting behavior is undefined. Some implementations will work correctly if you use memcpy
in both examples above. Others will fail for one or both of the two if you use memcpy
here instead of memmove
. This is a consequence of the fact C and C++ leave the behavior undefined for memcpy()
when the ranges overlap like this.
Upvotes: 13