Difference:
memcpy and Memmove () are library functions in the C language, in the header file string.h, the role is to copy the contents of a certain length of memory, the prototype is as follows:
void *memcpy (void *dst, const void *SRC, size_t count);
void *memmove (void *dst, const void *SRC, size_t count);
Their role is the same, the only difference is that when the memory local overlap, memmove guarantee that the results of the copy is correct, memcpy does not guarantee that the results of the copy is correct.
First, memcpy function
memcpy Prototypes:
void *memcpy (void *dest, const void *SRC, size_t n);
Describe:
The memcpy () function copies n bytes from src memory to the dest memory area, but the source and destination memory areas do not overlap.
return value:
The memcpy () function returns a pointer to Dest.
Second, memmove function
Memmovey Prototypes:
void *memmove (void *dest, const void *SRC, size_t n);
Describe:
The Memmove () function copies n bytes from src memory to a dest memory area, but the source and destination memory can overlap.
return value:
The Memmove function returns a pointer to Dest.
As can be seen from the above description, the only difference between the two is that when dealing with overlapping areas, memmove can correctly complete the corresponding copy, and memcpy cannot.
There are two scenarios for memory coverage:
Let's look at the implementation of the two functions of memcpy () and Memmove ():
void* my_memcpy (void* DST, const void* SRC, size_t N)
{
char *tmp = (char*) DST;
Char *s_src = (char*) src;
while (n--) {
*tmp++ = *s_src++;
}
return DST;
}
From the implementation, it can be seen that memcpy () is a byte from the left of memory to copy the contents of SRC into the dest memory, this implementation caused the second memory overlap in the diagram, the last two bytes of the copy value is obviously not the original value, The new value is changed to the first 2 bytes of SRC.
In the case of the first memory coverage, this copy of the memcpy is possible.
And Memmove is for the second memory coverage situation, the memcpy has been improved, the improved code is as follows:
void* My_memmove (void* DST, const void* SRC, size_t N)
{
char* s_dst;
char* s_src;
S_DST = (char*) DST;
S_SRC = (char*) src;
if (s_dst>s_src && (S_SRC+N>S_DST)) { //-------------------------The second memory coverage scenario.
s_dst = s_dst+n-1;
S_SRC = s_src+n-1;
while (n--) {
*s_dst--= *s_src--;
}
} else {
while (n--) {
*s_dst++ = *s_src++;
}
}
return DST;
}
Under the second memory cover scenario, memcpy will make an error, but Memmove will work correctly.
Enlighten