memcpy vs memmove
memcpy copies n bytes between non-overlapping regions. memmove copies n bytes and is defined when the regions overlap. Same speed in the non-overlap case on a good libc; different contracts.
Detailed Explanation
Both are in <string.h>:
void *memcpy(void *restrict dest, const void *restrict src, size_t n);
void *memmove(void *dest, const void *src, size_t n);
memcpy's restrict is the overlap ban. The library may load all of src and then store all of dest, or copy in whatever order vectorizes. If the regions overlap, the read of a later src byte may already have been overwritten. The standard says undefined behavior.
memmove must behave as if it copied through a temporary. Implementations check the pointer order and copy forward or backward so each byte is read before it is overwritten. You pay a branch and, on overlap, a slightly more careful loop.
When do they overlap? memmove(buf + 1, buf, n) shifts right. memmove(buf, buf + 1, n) shifts left. Any dest and src in the same array with |dest - src| < n overlap. Two malloc blocks do not overlap. A struct assignment of non-overlapping objects does not need memmove.
memcpy is also the blessed way to type-pun: copy an int's bytes into a float, or off an unaligned buffer into an aligned int. A pointer cast would be a strict-aliasing or alignment violation.
n == 0 is defined for both and copies nothing. NULL dest or src with n > 0 is undefined. NULL with n == 0 is a grey area; do not rely on it.
Prefer memmove when you are not sure. Prefer memcpy when overlap is impossible and you want the contract documented at the call. Do not roll your own byte loop without a reason; the libc versions are vectorized.
Code Examples
#include <stdio.h>
#include <string.h>
int main(void)
{
char a[] = "abcdef";
memmove(a + 1, a, 3); /* overlap: a[0..2] -> a[1..3] */
printf("%s\n", a); /* prints: aabcde */
return 0;
}#include <stdio.h>
#include <string.h>
#include <stdint.h>
int main(void)
{
unsigned char raw[4] = { 0x01, 0x00, 0x00, 0x00 };
uint32_t x;
memcpy(&x, raw, sizeof x); /* defined type-pun + unaligned src */
printf("%u\n", (unsigned)x); /* prints: 1 on little-endian */
return 0;
}Common Gotchas
`memcpy` on overlap is undefined behavior
it may appear to work and then fail after an optimizer change.
`strcpy` is not `memcpy`
it stops at `'\0'` and does not take a bound.
`memmove` is correct for non-overlap too
use it when the function cannot prove disjointness.