Memcpy vs Memmove
The C standard library (stdlib) facilitates two functions for copying memory regions, they are memcpy and memmove . The important difference is that memcpy does not behave correctly when dealing with overlapping regions. Let us understand it in detail with examples.
memcpy() is generally used to copy a portion of memory chuck from one location to another location. memcpy() works fine when there is no overlapping between source and destination. Lets consider a overlapping of buffer in the front side/lower side. Below picture shows the details.
Memcpy implementation in C
Output Elements : 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, After memcpy() Elements : 0, 3, 4, 5, 6, 7, 6, 7, 8, 9,
However memcpy() works fine here. Now consider a case where overlapping is there at the trailing side or in upper side of the memory.
Output Elements : 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, After memcpy() Elements : 0, 1, 2, 3, 4, 3, 4, 3, 4, 3,
Here result is not expected. From the above graphical view it is clear that some mechanism should be there to take care of the overlapping and displacement of elements should be in the reverse direction when overlapping is at the trailing side. Below diagram shows how it should be.
Memmove copies memory blocks from source location to destination location like memcpy but it also takes care of the overlapping. Copy of the memory bytes are done in non-destructive manner.
Memmove implementation in C
Output Elements : 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, After memmove() Elements : 0, 1, 2, 3, 4, 3, 4, 5, 6, 7,
NAME memcpy - copy area of memory bytes from source to destination. LIBRARY Standard C Library (libc, -lc) SYNOPSIS #include
void * memcpy(void * dst, const void * src, size_t n); DESCRIPTION The memcpy() function copies n bytes from memory from src location to memory pointed to dst. If dst and src area overlaps then behavior is undefined. Applications which might deal with dst and src might overlap should use memmove(3) instead. RETURN VALUE The memcpy() function returns the original value of dst.
NAME memmove - copies bytes from source to destination while taking care of overlapping. LIBRARY Standard C Library (libc, -lc) SYNOPSIS #include
void * memmove(void *dst, const void *src, size_t n); DESCRIPTION The memmove() function copies n bytes from src area to dst area. These two areas might overlap; the copy process always done in a non-destructive manner. RETURN VALUES The memmove() function returns the original value of dst.
About our authors: Team EQA
You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.
Questions index C Questions C++ Questions Win32 MFC COM/DCOM DLL Questions
Compilers & Editors
Download Visual Studio Download XCode Download Visual Studio Code Android studio install sdk Eclipse installer Best C compilers IDEs
Development system setup
Windows media creation tool MSDN subscription Ubuntu virtualbox
New updated posts
Why learn C? Draw on printer Memory leaks