memmove(3)

C library function

Copies n bytes from one area to another and gets the right result even when the two overlap. Returns the destination, like memcpy.

Synopsis
#include <string.h>
void *memmove(void *dest, const void *src, size_t n);

Description

memmove does the same job as memcpy(3), copying n bytes from src to dest, with one extra guarantee: the result is correct even when the two areas overlap. The C23 standard describes it with an image: the copy takes place “as if the n characters from the object pointed to by s2 are first copied into a temporary array”, then copied to the destination. The temporary array does not really exist, but the result is the same: no source byte is overwritten before it has been read.

That is the whole difference from memcpy. If you shift data forward inside one array with memcpy, you overwrite source bytes before you have copied them, and the end comes out corrupted. A memmove implementation checks which way the areas overlap and copies from back to front when it has to.

Return value

memmove returns dest, like memcpy.

Example

A shift by two positions inside one array, the classic case where memcpy would fail:

memmove.c
#include <stdio.h>#include <string.h>
int main(void){    char buf[] = "0123456789";
    memmove(buf + 2, buf, 5);    printf("%s\n", buf);    return 0;}
Terminal
$ gcc -Wall -Wextra -g memmove.c -o memmove$ ./memmove0101234789

The first five bytes (01234) were copied two places further along without stepping on each other.

Pitfalls

  • Reaching for memmove by default, “just in case”: when you know the areas do not overlap, memcpy states that assumption and can be faster.

  • Thinking memmove adds a '\0': it does not. It copies bytes, like memcpy.

  • Getting the size n wrong: it counts bytes, not elements. For an array of int, it is n * sizeof(int).

C

memmove

Write gm_memmove, which copies back to front when dst sits after src, so overlapping regions come out right.

Open the exercise

Now write it yourself.