The below code snippet shows the implementation of memmove()
.
void my_memmove(void* dest, const void* src, size_t size)
{
unsigned int i;
char* d = (char*)dest;
char* s = (char*)src;
if( s > d )
{
for( i = 0; s[i] && i < size; ++i )
d[i] = s[i];
}
else
for( i = size-1; d[i] && i >= 0; --i )
d[i] = s[i];
}
int main()
{
char my_str[] = "abcdefgh";
char str[] = "abcdefgh";
my_memmove(my_str+1, my_str, 4);
memmove(str+1, str, 4);
printf("%s %s\n", my_str, str);
return 0;
}
I am getting the output as:
aabcdfgh
Why my_memmove() is not working correctly ( It changes the my_str such that it outputs empty string )?
For an unsigned integer, the condition i >= 0
is always true. It's better to write the idiomatic loop with the "-1" reversal bias:
for (i = 0; i != size; ++i)
d[size - i - 1] = s[size - i - 1];
Also, the additional condition s[i] &&
just looks plain wrong.