Header files: #include <string.h>
Memmove () is used to replicate memory content, and its prototype is:
void * Memmove (void *dest, const void *SRC, size_t num);
Memmove () is similar to memcpy () in that it is used to replicate the memory content referred to by src before the Num bytes to the address referred to by dest. The difference is that memmove () is more flexible, and memmove () can still be handled correctly when the memory areas referred to by SRC and dest overlap, but the execution efficiency is slightly slower than using memcpy ().
For more information please refer to memcpy () below for an example:
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- int main ()
- {
- Char str[] = "Memmove can be very useful ...";
- memmove (str+20, str+15,one);
- puts (str);
- system("pause");
- return 0;
- }
Operation Result:
Memmove can very very useful.
This code is a good illustration of what happens when memory overlaps: first copy the content to a buffer-like place, and then overwrite the memory that dest points to with the contents of the buffer, as you can see.
The difference between Memcopy and Memmove (written, interview)
The memcopy and Memmove functions read the source code for two functions under Linux.
The two functions are defined in the header file string.h, and the function prototypes are:
void * __cdecl memcpy (void * dst,const void * src,size_t count);
void * __cdecl memmove (void * dst,const void * src,size_t count);
The implementation code is as follows:
void * __cdecl memcpy (void * dst,const void * src,size_t count)
{
void * ret = DST;
while (count--)
{// Note that the memcpy function does not address The issue of whether the DST and src regions overlap
* (char *) DST = * (char *) src;
DST = (char *) DST + 1;
src = (char *) src + 1;
}
return (ret);
}
void * __cdecl memmove (void * dst,const void * src,size_t count)
{
void * ret = DST;
if (DST <= src | | (char *) DST >= ((char *) SRC + count))
{
// if DST and SRC area does not overlap, copy from start
while (count--)
{
* (char *) DST = * (char *) src;
DST = (char *) DST + 1;
src = (char *) src + 1;
}
}
Else
{// If the DST and SRC regions intersect, the starting position is copied from the tail to avoid data collisions
DST = (char *) DST + count-1;
src = (char *) src + count-1;
while (count--)
{
* (char *) DST = * (char *) src;
DST = (char *) dst-1;
src = (char *) src-1;
}
}
return (ret);
}
To summarize:
When the SRC and DST regions do not overlap, the two functions are exactly the same. The condition that the wood overlaps is: DST <= src | | (char *) DST >= ((char *) SRC + count. Otherwise, memcpy is not working properly, memmove can work properly.
The difference between memcpy and memmove