memcpy() and memmove()
memcpy does a mindless copy, regardless of whether there are shared bytes between the source and destination:
void *memcpy (void *dst, const void *src, size_t n)
{
char *a = dst;
const char *b = src;
while (n--)
{
*a++ = *b++;
}
return dst;
}
memmove does backward copy and takes care of overwritten value of shared bytes:
void *memmove(void *dst, const void *src, size_t n)
{
char *a = dst;
const char *b = src;
if (a <= b || b >= (a + n)) {
/* No overlap, use memcpy logic or can use memcpy itself(copy forward) */
while (n--)
*a++ = *b++;
}
else {
/* Overlap! Copy backward to fix */
a = a + n - 1;
b = b + n - 1;
while (n--)
*a-- = *b--;
}
return dst;
}
No comments:
Post a Comment