Search code examples
cmemmove

Why memmove() function works this way?


I was going through various questions related to memmove() vs memcpy() on Stack Overflow.

There was this post that implied that if the source address (data to be copied from) is greater than destination address (data to be copied to), it will perform forward copying otherwise it will perform backward copying.

Why it is that way? I tried forward copying for both cases and that worked perfectly fine without any error.

Can you please elaborate? I'm not getting the reason.

EDIT: here's what i meant to say:

#include <memory.h> 
#include <string.h>
#include <stdio.h>

void *memmoveCustom(void *dest, const void *src, size_t n)
{
    unsigned char *pd = (unsigned char *)dest;
    const unsigned char *ps = (unsigned char *)src;
    if ( ps < pd )
        for (pd += n, ps += n; n--;)
            *--pd = *--ps;
    else
        while(n--)
            *pd++ = *ps++;
    return dest;
}

int main( void )
{
    printf( "The string: %s\n", str1 );

    memmoveCustom( str1 + 1, str1, 9 );
    printf( "Implemented memmove output: %s\n", str1 );

    getchar();
}

Above program is an example code that is implementing a custom memmove() function. Inside the function, you can see when the source address was greater than destination address, it performed forward copying otherwise it added n-location to the existing addresses and performed the copying from backward. That's it.


Solution

  • if the source address(data to be copied from) is greater than destination address(data to be copied to), it will perform forward copying otherwise it will perform backward copying.

    This is important only when from and to ranges overlap. For non-overlapping ranges the direction of copying does not matter.

    It matters for overlapping ranges because if you start copying from the beginning, you will destroy the source data before you get to copying it.