In this chapter, the three functions of memcpy, memmove and memcmp are explained in detail and simulated;
The focus of this chapter: the use methods and precautions of 3 common memory functions and learn to simulate their implementation;
If you think the article is good, I look forward to your one-click three-link. Your encouragement is the source of motivation for my creation. Let us work together, run together, and let us meet at the top! ! !
1. memcpy function (memory copy function)
Function introduction
Example of use:
Analog implementation of memcpy:
void* memcpy(void* dst, const void* src, size_t count)
{
void* ret = dst;
assert(dst);
assert(src);
while (count--)
{
*(char*)dst = *(char*)src;
dst = (char*)dst + 1;
src = (char*)src + 1;
}
return(ret);
}
It is to copy the source content byte by byte to the target space, so the forced type conversion is char*;
2. memmove function (memory movement function)
Function introduction
The usage of memcpy and memmove functions is the same; the functions are different;
1. The memmove function can not only copy non-overlapping memory, but also copy overlapping memory.
Example usage of memmove
When the memmove function is used to copy overlapping memory
Simulation implementation of memmove function
void* memmove(void* dst, const void* src, size_t count)
{
void* ret = dst;
if (dst <= src || (char*)dst >= ((char*)src + count))
{
while (count--)
{
*(char*)dst = *(char*)src;
dst = (char*)dst + 1;
src = (char*)src + 1;
}
}
else
{
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);
}
Parse:
For example,
put 1 2 3 4 5 in arr[]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10} in the position of 3 4 5 6 7, if we still use the previous The first step of the idea of memcpy
: Put 1 on 3, it becomes 1 2 1 4 5 6 7 8 9 10
The second step: Put 2 on 4, it becomes 1 2 1 2 5 6 7 8 9
10 Three steps: We need to put 3 on 5, but we have already changed 3 in the first step, so this kind of thinking doesn't work;
Memmove simulation implementation idea:
3. memcmp function (memory comparison function)
Function introduction
Compare num bytes starting from ptr1 and ptr2 pointers
Use sample code:
int main()
{
char buffer1[] = "DWgaOtP12df0";
char buffer2[] = "DWGAOTP12DF0";
int n;
n = memcmp(buffer1, buffer2, sizeof(buffer1));
if (n > 0)
{
printf("'%s' is greater than '%s'.\n", buffer1, buffer2);
}
else if (n < 0)
{
printf("'%s' is less than '%s'.\n", buffer1, buffer2);
}
else
{
printf("'%s' is the same as '%s'.\n", buffer1, buffer2);
}
return 0;
}
operation result:
end of this chapter~