</>EmbeddedInterview

What is the difference between memcpy and memmove?

EasyPointers & Memory

Short answer: Both copy n bytes from source to destination. memcpy assumes the two regions do not overlap; if they do, the behaviour is undefined. memmove handles overlap correctly, as if the data were first copied to a temporary buffer, usually by copying backwards when the destination is above the source.

char buf[] = "abcdef";

memmove(buf + 2, buf, 4);   /* "ababcd" - correct */
memcpy(buf + 2, buf, 4);    /* undefined: may give "ababab" with a simple forward copy */

Why a forward copy breaks with overlap: copying buf[0..3] to buf[2..5] one byte at a time from the front overwrites buf[2] and buf[3] before they are read.

How memmove decides direction

void *my_memmove(void *dst, const void *src, size_t n)
{
    unsigned char *d = dst;
    const unsigned char *s = src;
    if (d < s) {
        while (n--) *d++ = *s++;          /* copy forward */
    } else if (d > s) {
        d += n; s += n;
        while (n--) *--d = *--s;          /* copy backward */
    }
    return dst;
}

(Comparing pointers into different objects with < is technically unspecified in C; library implementations do it with integer addresses.)

When to use which

  • memcpy when the buffers are distinct (most cases); it can be slightly faster because it may copy in any order and use the widest possible loads.
  • memmove when shifting data inside one buffer: removing bytes from the front of a receive buffer, inserting into an array, scrolling a display buffer.

Embedded notes

  • Neither function respects volatile or peripheral access widths: do not use them to copy to or from hardware registers or device memory; write an explicit loop with volatile accesses of the right width.
  • For large copies on an MCU, a DMA memory-to-memory transfer can free the CPU.
  • Compilers often replace small fixed-size memcpy calls with inline loads and stores, and they may also turn a hand-written copy loop into a memcpy call (which matters if you are writing the memcpy implementation itself: build it with -fno-builtin or -ffreestanding).