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?
In human memory research, concurrent overlap, or task appropriate processing, is a type of processing overlap between an activity engaged in before the prospective memory is to be remembered and a cue that directs attention towards the prospective memory.
If the memory segments coincide at some point, a "overlapping" would occur. Imagine a memory segment starts at address 0x51, and the other starts at address 0x70, and you try to copy 50 bytes from 0x51 to 0x70... at some point, the process will start reading from address at 0x70, and copying to address 0x8F.
The CRT function memcpy doesn't support overlapping memory. The CRT provides an alternative to memcpy that does support overlapping memory: memmove .
memmove() is used to copy a block of memory from a location to another. It is declared in string.h. // Copies "numBytes" bytes from address "from" to address "to" void * memmove(void *to, const void *from, size_t numBytes);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With