Question

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 )?

Was it helpful?

Solution

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.

OTHER TIPS

You are assuming that src and dest are pointing to points in the same memory block.

...
char* d = (char*)dest;
char* s = (char*)src;

if( s > d )
...

This means if anyone ever calls your function with src and dest pointing to 2 different locations in memory, you will get undefined behavior.

This is very very bad, just use the built-in memmove().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top