Difference between memcpy and memmove in C with example?

Answer:

Answer



Check this link.It has a good explanation of how memcpy and memmove works.
http://learnwithtechies.com/index.php/component/content/article/4-c/13-difference-between-memcpy-and-memmove







Its similar to typing without insert key ON and OFF
str1="strings are good");
memmove(str1+8,str1+11,4);
returns------ strings are are good
memcpy(str+8,str1+11,4)
returns------ strings are read


memcpy - just copies form source to destination.
memmove - copies from source to destination if buffers overlap ,every character is read before another character is written to the same location..










above example will give same output in both the cases as source and destination areas doesn't overlap also `are' will not be appended as claimed in above example.


instead use below example:


str = "0123456789"
memmove(str+2, str+1, 3);
returns: 0112356789

memcpy(str+2, str+1, 3);
returns: 0111356789


As we could see in second example of memcpy `1' is copied twice, from memory-location: 1 and then from memory-location:2 which was updated to `1' by memcpy, where as memmove uses a temporary buffer hence this problem didn't occur.

____________________________________________________________________

memcpy() copies the bytes of data between memory blocks. If the block of memory overlaps, the function might not work properly. Use memmove() to deal with overlapping memory blocks.

memmove() is very much like memcpy() but very flexible as it handles overlapping of memory blocks.

example :
char msg[50] = "abcdefghijklmnopqrstuvwxyz";
char temp[50];
main()
{
strcpy(temp, msg);
printf("Original Msg = %s\n",temp);

memcpy(temp+4, temp+16, 10);
printf("After memcpy without overlap = %s\n",temp);
strcpy(temp , msg);
memcpy(temp+6, temp+4, 10);
printf("After memcpy with overlap = %s\n",temp);

strcpy(temp, msg);
printf("Original Msg = %s\n",temp);

memmove(temp+4, temp+16, 10);
printf("After memmove without overlap = %s\n",temp);
strcpy(temp , msg);
memmove(temp+6, temp+4, 10);
printf("After memmove with overlap = %s\n",temp);
}

Original Msg = abcdefghijklmnopqrstuvwxyz
After memcpy without overlap = abcdqrstuvwxyzopqrstuvwxyz
After memcpy with overlap = abcdefefefefefefqrstuvwxyz

Original Msg = abcdefghijklmnopqrstuvwxyz
After memmove without overlap = abcdqrstuvwxyzopqrstuvwxyz
After memmove with overlap = abcdefefghijklmnqrstuvwxyz
Note: There are comments associated with this question. See the discussion page to add to the conversation.
First answer by ID2171334657. Last edit by Cexpert. Contributor trust: 0 [recommend contributor recommended]. Question popularity: 12 [recommend question].