How to implement memmove() function ?

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 the source and destination addresses are overlapping.


#include
#include

void myMemMove(void *dest, void *src, size_t n)
{
   char *csrc = (char *)src;
   char *cdest = (char *)dest;
   int i;
   char* temp = new char[n];
   for(i = 0; i < n; i++){
       temp[i] = csrc[i];
   }
   
    for(i = 0; i < n; i++){
       cdest[i] = temp[i];
   }
   
   delete []temp;
}

// Driver program
int main()
{
   char csrc[100] = "FunctionAdd";
   myMemMove(csrc+8, csrc, strlen(csrc)+1);
   printf("%s", csrc);
   return 0;
}

Comments