I am trying to implement my own memmove function. I am trying to optimize it instead of copying byte by byte. Here is my implementation:
void* my_memmove(void *dest, const void *src, size_t len) {
if((uintptr_t)dest < (uintptr_t)src)
return memcpy(dest,src,len);
long *pdest = (long*)dest +len;
const long *psrc = (const long*)src+len;
if(!((uintptr_t)dest+len & (sizeof(long)-1)) &&
!((uintptr_t)src+len & (sizeof(long)-1))) {
while(len >= sizeof(long)) {
*--pdest = *--psrc;
len-=sizeof(long);
}
}
char *pdest2 = (char*)pdest;
const char *psrc2= (const char*)psrc;
while(len) {
*--pdest2 = *--psrc2;
len--;
}
return dest;
}
Any input on how I can make this better or if the existing code has some issues?
There is a bug in the code calling
memcpy.I changed your code like
Output:
So you call
memcpywith overlapping areas.Another bug...
What do you expect from this line:
Assume
destis 0x1000 andlenis 1. It seems you expect the value0x1001but try this:Output on my system:
which is not what you want.