What is memmove()?

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. For example consider below program. 

C
// Sample program to show that memcpy() can lose data. 
#include <stdio.h> 
#include <string.h> 
int main() 
{ 
char csrc[100] = "Geeksfor"; 
memcpy(csrc+5, csrc, strlen(csrc)+1); 
printf("%s", csrc); 
return 0; 
} 

Output:

GeeksGeeksGeek

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

C
// Sample program to show that memmove() is better than memcpy() 
// when addresses overlap. 
#include <stdio.h> 
#include <string.h> 
int main() 
{ 
char csrc[100] = "Geeksfor"; 
memmove(csrc+5, csrc, strlen(csrc)+1); 
printf("%s", csrc); 
return 0; 
} 

Output:

GeeksGeeksfor

Write your own memcpy() and memmove()

The memcpy function is used to copy a block of data from a source address to a destination address. Below is its prototype.

void * memcpy(void * destination, const void * source, size_t num);

The idea is to simply typecast given addresses to char *(char takes 1 byte). Then one by one copy data from source to destination. Below is implementation of this idea. 

C
// A C implementation of memcpy() 
#include<stdio.h> 
#include<string.h> 

void myMemCpy(void *dest, void *src, size_t n) 
{ 
// Typecast src and dest addresses to (char *) 
char *csrc = (char *)src; 
char *cdest = (char *)dest; 

// Copy contents of src[] to dest[] 
for (int i=0; i<n; i++) 
    cdest[i] = csrc[i]; 
} 

// Driver program 
int main() 
{ 
char csrc[] = "w3wiki"; 
char cdest[100]; 
myMemCpy(cdest, csrc, strlen(csrc)+1); 
printf("Copied string is %s", cdest); 

int isrc[] = {10, 20, 30, 40, 50}; 
int n = sizeof(isrc)/sizeof(isrc[0]); 
int idest[n], i; 
myMemCpy(idest, isrc, sizeof(isrc)); 
printf("\nCopied array is "); 
for (i=0; i<n; i++) 
    printf("%d ", idest[i]); 
return 0; 
} 

Output:

Copied string is w3wiki
Copied array is 10 20 30 40 50

Time Complexity: O(n)

Auxiliary Space: O(1)

Similar Reads

What is memmove()?

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. For example consider below program....

How to implement memmove()?

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....

Contact Us