The difference is simple. You can see the man manual of these two functions. To put it simply, memmove moves a bunch of bytes from SRC to DST. memcpy copies a bunch of bytes from SRC to DST. The biggest difference is: memmove copies a bunch of bytes to a temporary array and then writes the temporary array to DST. memcpy does not have this logic, directly reads data from SRC one byte and writes data to DST one byte at the same time. This leads to a fundamental difference:
Memcpy is not suitable for or cannot handle the case where the memory of SRC and DST overlaps (overlap. Because memcpy directly copies data from SRC and writes the data to DST, if the memory of SRC and DST overlaps, Data Writing errors may occur. For example:
-
Code: select all
-
src.........\0
dst.........\0
In this case, due to the overlapping parts of DST and SRC, when writing DST, the contents in SRC are also rewritten, so that the copied contents are not correct.
This is the difference between the two. The following code is provided to show more explicit usage of the two functions. The Code comes from the lftp source code. I also read the source code to see the differences between the two functions.
-
Code: select all
-
/*
* replace string mem by string s, len is the length of string s
* NOTE: use memmove while mem & s has overlaps and use
* memcpy while they have no overlaps
*/
char *xstrset(char *&mem,const char *s,size_t len)
{
if(!s)
{
xfree(mem);
return mem=0;
}
#ifdef MEM_DEBUG
printf("xstrset \"%.*s\"\n",len,s);
#endif
if(s==mem)
{
mem[len]=0;
return mem;
}
size_t old_len=(mem?strlen(mem)+1:0);
// s & mem have overlaps
// and s's start point is in mem's range
// so use memmove, cannot use memcpy
// mem.........\0
// s..............\0
// after memmove
// mem..............\0 -- mem has new contents(s)
if(mem && s>mem && s<mem+old_len)
{
memmove(mem,s,len);
mem[len]=0;
return mem;
}
// mem & s have no overlaps and the mem is too small
// mem cannot accommodate the whole `s' so realloc the memory
if(old_len<len+1)
mem=(char*)xrealloc(mem,len+1);
memcpy(mem,s,len);
mem[len]=0;
return mem;
}
This code is a function that copies s to mem. Both S and MEM indicate string, and Len indicates the length of string S. In the function, xmalloc and xfree are equivalent to malloc and free, but some encapsulation is done, and a counter is added to track the number of applications and releases. The key is to look at several if judgments in this function. These if judgments determine whether the MEM and S overlap and call different functions.