Wednesday 28 June 2017

memmove() function

memmove() offers guaranteed behavior if the source and destination arguments overlap. memcpy() makes no such guarantee.
memmove() is similar to memcpy() as it also copies data from a source to destination. memcpy() leads to problems when source and destination addresses overlap as memcpy() simply copies data one by one from one location to another.


Since the input addresses are overlapping, the above program overwrites the original string and causes data loss.


The trick here is to use a temp array instead of directly copying from src to dest. The use of temp array is important to handle cases when source and destination addresses are overlapping.



 
void *mymemmove(void *to, const void *from, size_t size)

{

        

 char *p2 = from;
   char *tmp = new char[size];
   for(int i=0; i   {
           tmp[i] = p2[i];
   }

   for(int j=0; j   {
           p1[j] = tmp[j];
   }

   delete [] tmp;
}


Above method is not optimized and it double copy the data;


void *mymemmove(void *to, const void *from, size_t size)
{
       char *p1 = to;
        char *p2 = from;
        p2 = p2 + size;
        while(p2!=from && --p2 !=to);
        if(p2 != from)
        {
                //overlap detected;
                p2 = from;
                p1 = to;
                p2 = p2+size;
                p1 = p1+size;
                while(size-- != 0)
                {
                        *--p1 = *--p2;
                };
        }
        else
        {
                    mymemcpy(to, from, size);
        }


}


void mymemcpy(char *to, char *from, int size)
{
   char *p1 = to;
   char *p2 = from;

   for(int i=0; i   {
           p1[i] = p2[i];
   }
}




 


int main(int argc, char *argv[])
{
        char *p1 = NULL;
        p1 = (char*)malloc(12);
        strcpy(p1,"ABCDEFGHI");
        char *p2
         int size = 10;

        p2 = p1 + 2;
        printf("before to:%s\n", p2); //ABCDEFGHI
        //strncpy(p2,p1,size);

       mymemcpy(p2,p1,size);
  
               printf("after memcpy to:%s\n", p2);//ABABABABAB
       
          mymemmove(p2,p1,size);

        printf("after to:%s\n", p2); //ABCDEFGHI
}

No comments:

Post a Comment